From 6b0da3d08b3152990d6db9a916d57d2295dd8227 Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Tue, 12 Nov 2019 23:18:48 +0000 Subject: [PATCH 1/9] Don't extend ActivatableViewAndModel when the model is empty Remove the no-arg constructor from ActivatableViewAndModel, which sets a dummy Activatable singleton as the model. (Since the model type param can't be checked at runtime, improper use of the constructor could cause heap pollution.) Instead, extend 'ActivatableView' consistently, as other views without a model currently do. --- .../java/bisq/desktop/common/model/Activatable.java | 12 ------------ .../desktop/common/view/ActivatableViewAndModel.java | 5 ----- .../src/main/java/bisq/desktop/main/dao/DaoView.java | 5 ++--- .../bisq/desktop/main/dao/bonding/BondingView.java | 4 ++-- .../bisq/desktop/main/dao/burnbsq/BurnBsqView.java | 4 ++-- .../bisq/desktop/main/dao/economy/EconomyView.java | 4 ++-- .../desktop/main/dao/governance/GovernanceView.java | 4 ++-- .../bisq/desktop/main/dao/monitor/MonitorView.java | 4 ++-- .../bisq/desktop/main/dao/wallet/BsqWalletView.java | 4 ++-- .../main/java/bisq/desktop/main/funds/FundsView.java | 5 ++--- .../java/bisq/desktop/main/market/MarketView.java | 5 ++--- .../bisq/desktop/main/portfolio/PortfolioView.java | 5 ++--- .../bisq/desktop/main/settings/SettingsView.java | 5 ++--- .../bisq/desktop/main/settings/about/AboutView.java | 5 ++--- .../main/settings/network/NetworkSettingsView.java | 5 ++--- .../java/bisq/desktop/main/support/SupportView.java | 5 ++--- 16 files changed, 28 insertions(+), 53 deletions(-) diff --git a/desktop/src/main/java/bisq/desktop/common/model/Activatable.java b/desktop/src/main/java/bisq/desktop/common/model/Activatable.java index e21ff5ec9fe..69ff8fca271 100644 --- a/desktop/src/main/java/bisq/desktop/common/model/Activatable.java +++ b/desktop/src/main/java/bisq/desktop/common/model/Activatable.java @@ -22,16 +22,4 @@ public interface Activatable { void _activate(); void _deactivate(); - - - Activatable NO_OP_INSTANCE = new Activatable() { - @Override - public void _activate() { - } - - @Override - public void _deactivate() { - } - }; - } diff --git a/desktop/src/main/java/bisq/desktop/common/view/ActivatableViewAndModel.java b/desktop/src/main/java/bisq/desktop/common/view/ActivatableViewAndModel.java index e50d96e2dde..433a19d1367 100644 --- a/desktop/src/main/java/bisq/desktop/common/view/ActivatableViewAndModel.java +++ b/desktop/src/main/java/bisq/desktop/common/view/ActivatableViewAndModel.java @@ -29,11 +29,6 @@ public ActivatableViewAndModel(M model) { super(checkNotNull(model, "Model must not be null")); } - public ActivatableViewAndModel() { - //noinspection unchecked - this((M) Activatable.NO_OP_INSTANCE); - } - @Override protected void prepareInitialize() { if (root != null) { diff --git a/desktop/src/main/java/bisq/desktop/main/dao/DaoView.java b/desktop/src/main/java/bisq/desktop/main/dao/DaoView.java index 3003ba1f41d..7fb1c5bf789 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/DaoView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/DaoView.java @@ -18,8 +18,7 @@ package bisq.desktop.main.dao; import bisq.desktop.Navigation; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -53,7 +52,7 @@ import javafx.beans.value.ChangeListener; @FxmlView -public class DaoView extends ActivatableViewAndModel { +public class DaoView extends ActivatableView { @FXML private Tab bsqWalletTab, proposalsTab, bondingTab, burnBsqTab, daoNewsTab, monitorTab, factsAndFiguresTab; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/bonding/BondingView.java b/desktop/src/main/java/bisq/desktop/main/dao/bonding/BondingView.java index 96a37d93b49..b2d18cbd9ba 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/bonding/BondingView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/bonding/BondingView.java @@ -18,7 +18,7 @@ package bisq.desktop.main.dao.bonding; import bisq.desktop.Navigation; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -49,7 +49,7 @@ import javax.annotation.Nullable; @FxmlView -public class BondingView extends ActivatableViewAndModel { +public class BondingView extends ActivatableView { private final ViewLoader viewLoader; private final Navigation navigation; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/burnbsq/BurnBsqView.java b/desktop/src/main/java/bisq/desktop/main/dao/burnbsq/BurnBsqView.java index 925eaeb2061..59b1e280852 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/burnbsq/BurnBsqView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/burnbsq/BurnBsqView.java @@ -18,7 +18,7 @@ package bisq.desktop.main.dao.burnbsq; import bisq.desktop.Navigation; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -44,7 +44,7 @@ import java.util.List; @FxmlView -public class BurnBsqView extends ActivatableViewAndModel { +public class BurnBsqView extends ActivatableView { private final ViewLoader viewLoader; private final Navigation navigation; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/economy/EconomyView.java b/desktop/src/main/java/bisq/desktop/main/dao/economy/EconomyView.java index e1ae7977540..ce54dd63f05 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/economy/EconomyView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/economy/EconomyView.java @@ -18,7 +18,7 @@ package bisq.desktop.main.dao.economy; import bisq.desktop.Navigation; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -47,7 +47,7 @@ import java.util.List; @FxmlView -public class EconomyView extends ActivatableViewAndModel { +public class EconomyView extends ActivatableView { private final ViewLoader viewLoader; private final Navigation navigation; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/governance/GovernanceView.java b/desktop/src/main/java/bisq/desktop/main/dao/governance/GovernanceView.java index d8f31d6d94d..ac9faf64f97 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/governance/GovernanceView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/governance/GovernanceView.java @@ -18,7 +18,7 @@ package bisq.desktop.main.dao.governance; import bisq.desktop.Navigation; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -52,7 +52,7 @@ import java.util.List; @FxmlView -public class GovernanceView extends ActivatableViewAndModel implements DaoStateListener { +public class GovernanceView extends ActivatableView implements DaoStateListener { private final ViewLoader viewLoader; private final Navigation navigation; private final DaoFacade daoFacade; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/monitor/MonitorView.java b/desktop/src/main/java/bisq/desktop/main/dao/monitor/MonitorView.java index 93de1642514..23f94d3f4d1 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/monitor/MonitorView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/monitor/MonitorView.java @@ -18,7 +18,7 @@ package bisq.desktop.main.dao.monitor; import bisq.desktop.Navigation; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -45,7 +45,7 @@ import java.util.List; @FxmlView -public class MonitorView extends ActivatableViewAndModel { +public class MonitorView extends ActivatableView { private final ViewLoader viewLoader; private final Navigation navigation; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/wallet/BsqWalletView.java b/desktop/src/main/java/bisq/desktop/main/dao/wallet/BsqWalletView.java index 81e639d25fe..1c33c4cb82c 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/wallet/BsqWalletView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/wallet/BsqWalletView.java @@ -18,7 +18,7 @@ package bisq.desktop.main.dao.wallet; import bisq.desktop.Navigation; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -47,7 +47,7 @@ import java.util.List; @FxmlView -public class BsqWalletView extends ActivatableViewAndModel { +public class BsqWalletView extends ActivatableView { private final ViewLoader viewLoader; private final Navigation navigation; diff --git a/desktop/src/main/java/bisq/desktop/main/funds/FundsView.java b/desktop/src/main/java/bisq/desktop/main/funds/FundsView.java index 9ed0ae39196..425b5bdd912 100644 --- a/desktop/src/main/java/bisq/desktop/main/funds/FundsView.java +++ b/desktop/src/main/java/bisq/desktop/main/funds/FundsView.java @@ -18,8 +18,7 @@ package bisq.desktop.main.funds; import bisq.desktop.Navigation; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -43,7 +42,7 @@ import javafx.beans.value.ChangeListener; @FxmlView -public class FundsView extends ActivatableViewAndModel { +public class FundsView extends ActivatableView { @FXML Tab depositTab, withdrawalTab, reservedTab, lockedTab, transactionsTab; diff --git a/desktop/src/main/java/bisq/desktop/main/market/MarketView.java b/desktop/src/main/java/bisq/desktop/main/market/MarketView.java index e928d6334b8..535e61db449 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/MarketView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/MarketView.java @@ -18,8 +18,7 @@ package bisq.desktop.main.market; import bisq.desktop.Navigation; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -65,7 +64,7 @@ import java.util.stream.Collectors; @FxmlView -public class MarketView extends ActivatableViewAndModel { +public class MarketView extends ActivatableView { @FXML Tab offerBookTab, tradesTab, spreadTab; private final ViewLoader viewLoader; diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/PortfolioView.java b/desktop/src/main/java/bisq/desktop/main/portfolio/PortfolioView.java index 3bf9ceca8ca..acfd093b2ec 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/PortfolioView.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/PortfolioView.java @@ -18,8 +18,7 @@ package bisq.desktop.main.portfolio; import bisq.desktop.Navigation; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -50,7 +49,7 @@ import java.util.List; @FxmlView -public class PortfolioView extends ActivatableViewAndModel { +public class PortfolioView extends ActivatableView { @FXML Tab openOffersTab, pendingTradesTab, closedTradesTab; diff --git a/desktop/src/main/java/bisq/desktop/main/settings/SettingsView.java b/desktop/src/main/java/bisq/desktop/main/settings/SettingsView.java index ba81800a95e..523b74dc5be 100644 --- a/desktop/src/main/java/bisq/desktop/main/settings/SettingsView.java +++ b/desktop/src/main/java/bisq/desktop/main/settings/SettingsView.java @@ -18,8 +18,7 @@ package bisq.desktop.main.settings; import bisq.desktop.Navigation; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -42,7 +41,7 @@ import javafx.beans.value.ChangeListener; @FxmlView -public class SettingsView extends ActivatableViewAndModel { +public class SettingsView extends ActivatableView { @FXML Tab preferencesTab, networkTab, aboutTab; private final ViewLoader viewLoader; diff --git a/desktop/src/main/java/bisq/desktop/main/settings/about/AboutView.java b/desktop/src/main/java/bisq/desktop/main/settings/about/AboutView.java index 6bdc2787384..2414ac261e5 100644 --- a/desktop/src/main/java/bisq/desktop/main/settings/about/AboutView.java +++ b/desktop/src/main/java/bisq/desktop/main/settings/about/AboutView.java @@ -17,8 +17,7 @@ package bisq.desktop.main.settings.about; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.FxmlView; import bisq.desktop.components.HyperlinkWithIcon; import bisq.desktop.components.TitledGroupBg; @@ -41,7 +40,7 @@ import static bisq.desktop.util.FormBuilder.addTitledGroupBg; @FxmlView -public class AboutView extends ActivatableViewAndModel { +public class AboutView extends ActivatableView { private int gridRow = 0; diff --git a/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java b/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java index 2ea797e3cf8..4f98f015e09 100644 --- a/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java +++ b/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java @@ -18,8 +18,7 @@ package bisq.desktop.main.settings.network; import bisq.desktop.app.BisqApp; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.FxmlView; import bisq.desktop.components.AutoTooltipButton; import bisq.desktop.components.AutoTooltipLabel; @@ -74,7 +73,7 @@ import java.util.stream.Collectors; @FxmlView -public class NetworkSettingsView extends ActivatableViewAndModel { +public class NetworkSettingsView extends ActivatableView { @FXML TitledGroupBg p2pHeader, btcHeader; diff --git a/desktop/src/main/java/bisq/desktop/main/support/SupportView.java b/desktop/src/main/java/bisq/desktop/main/support/SupportView.java index f739f27c8a4..0268b6e2c96 100644 --- a/desktop/src/main/java/bisq/desktop/main/support/SupportView.java +++ b/desktop/src/main/java/bisq/desktop/main/support/SupportView.java @@ -18,8 +18,7 @@ package bisq.desktop.main.support; import bisq.desktop.Navigation; -import bisq.desktop.common.model.Activatable; -import bisq.desktop.common.view.ActivatableViewAndModel; +import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.CachingViewLoader; import bisq.desktop.common.view.FxmlView; import bisq.desktop.common.view.View; @@ -62,7 +61,7 @@ import javafx.collections.MapChangeListener; @FxmlView -public class SupportView extends ActivatableViewAndModel { +public class SupportView extends ActivatableView { @FXML Tab tradersMediationDisputesTab, tradersRefundDisputesTab, tradersArbitrationDisputesTab; From 2f61b025f549a06a9e9b2cebd6862b56bb639310 Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Fri, 15 Nov 2019 15:06:07 +0000 Subject: [PATCH 2/9] Improve type safety of the fluent interface of Overlay Refactor all the unchecked casts from Overlay to T into a single private cast() method. Also add a runtime type check to the constructor to prevent creation of window objects of the form "A extends Overlay" for unrelated A & B, as such casts would then subvert the type system. --- .../bisq/desktop/main/overlays/Overlay.java | 119 ++++++++---------- .../desktop/main/overlays/TabbedOverlay.java | 2 +- .../desktop/main/overlays/popups/Popup.java | 5 +- .../desktop/main/overlays/OverlayTest.java | 47 +++++++ 4 files changed, 100 insertions(+), 73 deletions(-) create mode 100644 desktop/src/test/java/bisq/desktop/main/overlays/OverlayTest.java diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/Overlay.java b/desktop/src/main/java/bisq/desktop/main/overlays/Overlay.java index 2794c16d36f..0053c087aaa 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/Overlay.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/Overlay.java @@ -29,14 +29,16 @@ import bisq.core.app.BisqEnvironment; import bisq.core.locale.GlobalSettings; +import bisq.core.locale.LanguageUtil; import bisq.core.locale.Res; import bisq.core.user.DontShowAgainLookup; -import bisq.core.locale.LanguageUtil; import bisq.common.Timer; import bisq.common.UserThread; import bisq.common.util.Utilities; +import com.google.common.reflect.TypeToken; + import org.apache.commons.lang3.StringUtils; import de.jensd.fx.fontawesome.AwesomeIcon; @@ -68,8 +70,8 @@ import javafx.geometry.HPos; import javafx.geometry.Insets; -import javafx.geometry.Pos; import javafx.geometry.NodeOrientation; +import javafx.geometry.Pos; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; @@ -93,7 +95,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j -public abstract class Overlay { +public abstract class Overlay> { /////////////////////////////////////////////////////////////////////////////////////////// // Enum @@ -185,12 +187,23 @@ protected enum Type { protected int maxChar = 1800; + private T cast() { + //noinspection unchecked + return (T) this; + } + /////////////////////////////////////////////////////////////////////////////////////////// // Public API /////////////////////////////////////////////////////////////////////////////////////////// public Overlay() { + //noinspection UnstableApiUsage + TypeToken typeToken = new TypeToken<>(getClass()) { + }; + if (!typeToken.isSupertypeOf(getClass())) { + throw new RuntimeException("Subclass of Overlay should be castable to T"); + } } public void show(boolean showAgainChecked) { @@ -266,26 +279,22 @@ protected void cleanup() { public T onClose(Runnable closeHandler) { this.closeHandlerOptional = Optional.of(closeHandler); - //noinspection unchecked - return (T) this; + return cast(); } public T onAction(Runnable actionHandler) { this.actionHandlerOptional = Optional.of(actionHandler); - //noinspection unchecked - return (T) this; + return cast(); } public T onSecondaryAction(Runnable secondaryActionHandlerOptional) { this.secondaryActionHandlerOptional = Optional.of(secondaryActionHandlerOptional); - //noinspection unchecked - return (T) this; + return cast(); } public T headLine(String headLine) { this.headLine = headLine; - //noinspection unchecked - return (T) this; + return cast(); } public T notification(String message) { @@ -294,8 +303,7 @@ public T notification(String message) { this.headLine = Res.get("popup.headline.notification"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T instruction(String message) { @@ -304,8 +312,7 @@ public T instruction(String message) { this.headLine = Res.get("popup.headline.instruction"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T attention(String message) { @@ -314,8 +321,7 @@ public T attention(String message) { this.headLine = Res.get("popup.headline.attention"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T backgroundInfo(String message) { @@ -324,8 +330,7 @@ public T backgroundInfo(String message) { this.headLine = Res.get("popup.headline.backgroundInfo"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T feedback(String message) { @@ -334,8 +339,7 @@ public T feedback(String message) { this.headLine = Res.get("popup.headline.feedback"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T confirmation(String message) { @@ -344,8 +348,7 @@ public T confirmation(String message) { this.headLine = Res.get("popup.headline.confirmation"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T information(String message) { @@ -354,8 +357,7 @@ public T information(String message) { this.headLine = Res.get("popup.headline.information"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T warning(String message) { @@ -365,8 +367,7 @@ public T warning(String message) { this.headLine = Res.get("popup.headline.warning"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T error(String message) { @@ -377,136 +378,116 @@ public T error(String message) { this.headLine = Res.get("popup.headline.error"); this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } @SuppressWarnings("UnusedReturnValue") public T showReportErrorButtons() { this.showReportErrorButtons = true; - //noinspection unchecked - return (T) this; + return cast(); } public T message(String message) { this.message = message; setTruncatedMessage(); - //noinspection unchecked - return (T) this; + return cast(); } public T closeButtonText(String closeButtonText) { this.closeButtonText = closeButtonText; - //noinspection unchecked - return (T) this; + return cast(); } public T useReportBugButton() { this.closeButtonText = Res.get("shared.reportBug"); this.closeHandlerOptional = Optional.of(() -> GUIUtil.openWebPage("https://bisq.network/source/bisq/issues")); - //noinspection unchecked - return (T) this; + return cast(); } public T useIUnderstandButton() { this.closeButtonText = Res.get("shared.iUnderstand"); - //noinspection unchecked - return (T) this; + return cast(); } public T actionButtonTextWithGoTo(String target) { this.actionButtonText = Res.get("shared.goTo", Res.get(target)); - //noinspection unchecked - return (T) this; + return cast(); } public T secondaryActionButtonTextWithGoTo(String target) { this.secondaryActionButtonText = Res.get("shared.goTo", Res.get(target)); - //noinspection unchecked - return (T) this; + return cast(); } public T closeButtonTextWithGoTo(String target) { this.closeButtonText = Res.get("shared.goTo", Res.get(target)); - //noinspection unchecked - return (T) this; + return cast(); } public T actionButtonText(String actionButtonText) { this.actionButtonText = actionButtonText; - //noinspection unchecked - return (T) this; + return cast(); } public T secondaryActionButtonText(String secondaryActionButtonText) { this.secondaryActionButtonText = secondaryActionButtonText; - //noinspection unchecked - return (T) this; + return cast(); } public T useShutDownButton() { this.actionButtonText = Res.get("shared.shutDown"); this.actionHandlerOptional = Optional.ofNullable(BisqApp.getShutDownHandler()); - //noinspection unchecked - return (T) this; + return cast(); } public T buttonAlignment(HPos pos) { this.buttonAlignment = pos; - return (T) this; + return cast(); } public T width(double width) { this.width = width; - //noinspection unchecked - return (T) this; + return cast(); } public T maxMessageLength(int maxChar) { this.maxChar = maxChar; - return (T) this; + return cast(); } public T showBusyAnimation() { this.showBusyAnimation = true; - //noinspection unchecked - return (T) this; + return cast(); } public T dontShowAgainId(String key) { this.dontShowAgainId = key; - //noinspection unchecked - return (T) this; + return cast(); } public T dontShowAgainText(String dontShowAgainText) { this.dontShowAgainText = dontShowAgainText; - //noinspection unchecked - return (T) this; + return cast(); } public T hideCloseButton() { this.hideCloseButton = true; - //noinspection unchecked - return (T) this; + return cast(); } public T useAnimation(boolean useAnimation) { this.useAnimation = useAnimation; - //noinspection unchecked - return (T) this; + return cast(); } public T setHeadlineStyle(String headlineStyle) { this.headlineStyle = headlineStyle; - //noinspection unchecked - return (T) this; + return cast(); } public T disableActionButton() { this.disableActionButton = true; - //noinspection unchecked - return (T) this; + return cast(); } diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/TabbedOverlay.java b/desktop/src/main/java/bisq/desktop/main/overlays/TabbedOverlay.java index 8dc484cfa66..94783de4b9a 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/TabbedOverlay.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/TabbedOverlay.java @@ -4,7 +4,7 @@ import javafx.scene.layout.Region; -public abstract class TabbedOverlay extends Overlay { +public abstract class TabbedOverlay> extends Overlay { protected JFXTabPane tabPane; diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/popups/Popup.java b/desktop/src/main/java/bisq/desktop/main/overlays/popups/Popup.java index 44b7b3518f3..3d64c001ae3 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/popups/Popup.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/popups/Popup.java @@ -22,7 +22,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class Popup extends Overlay { +// TODO: Type parameter is unused - remove: +public class Popup extends Overlay> { protected final Logger log = LoggerFactory.getLogger(this.getClass()); public Popup() { @@ -41,6 +42,4 @@ protected void onShow() { protected void onHidden() { PopupManager.onHidden(this); } - - } diff --git a/desktop/src/test/java/bisq/desktop/main/overlays/OverlayTest.java b/desktop/src/test/java/bisq/desktop/main/overlays/OverlayTest.java new file mode 100644 index 00000000000..5ee453bc0e5 --- /dev/null +++ b/desktop/src/test/java/bisq/desktop/main/overlays/OverlayTest.java @@ -0,0 +1,47 @@ +/* + * This file is part of Bisq. + * + * Bisq is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at + * your option) any later version. + * + * Bisq 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 Affero General Public + * License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Bisq. If not, see . + */ + +package bisq.desktop.main.overlays; + +import org.junit.Test; + +public class OverlayTest { + + @Test + public void typeSafeCreation() { + new A(); + new C(); + new D<>(); + } + + @Test(expected = RuntimeException.class) + public void typeUnsafeCreation() { + new B(); + } + + private static class A extends Overlay { + } + + private static class B extends Overlay { + } + + private static class C extends TabbedOverlay { + } + + private static class D extends Overlay> { + } +} From dd6db4687ca6de99c7d024aff32cdfed34898aec Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Fri, 15 Nov 2019 17:21:50 +0000 Subject: [PATCH 3/9] Improve type safety of ProtoUtil.collectionToProto(Collection) Add a Class parameter to the method, in order to avoid an unchecked cast to the Message type T. The cast was wrapped in a try-catch block, which is useless due to erasure, so use Class.cast(..) instead. --- common/src/main/java/bisq/common/proto/ProtoUtil.java | 9 ++++----- core/src/main/java/bisq/core/payment/PaymentAccount.java | 2 +- .../dispute/arbitration/ArbitrationDisputeList.java | 2 +- .../support/dispute/mediation/MediationDisputeList.java | 2 +- .../core/support/dispute/refund/RefundDisputeList.java | 2 +- core/src/main/java/bisq/core/trade/TradableList.java | 2 +- .../main/java/bisq/core/trade/protocol/ProcessModel.java | 3 ++- .../main/java/bisq/core/trade/protocol/TradingPeer.java | 3 ++- core/src/main/java/bisq/core/user/UserPayload.java | 4 ++-- 9 files changed, 15 insertions(+), 14 deletions(-) diff --git a/common/src/main/java/bisq/common/proto/ProtoUtil.java b/common/src/main/java/bisq/common/proto/ProtoUtil.java index 2cb80250bd9..6fd7b0f2e5d 100644 --- a/common/src/main/java/bisq/common/proto/ProtoUtil.java +++ b/common/src/main/java/bisq/common/proto/ProtoUtil.java @@ -77,15 +77,14 @@ public static > E enumFromProto(Class enumType, String name return result; } - public static Iterable collectionToProto(Collection collection) { + public static Iterable collectionToProto(Collection collection, Class messageType) { return collection.stream() .map(e -> { final Message message = e.toProtoMessage(); try { - //noinspection unchecked - return (T) message; - } catch (Throwable t) { - log.error("message could not be casted. message=" + message); + return messageType.cast(message); + } catch (ClassCastException t) { + log.error("Message could not be cast. message={}, messageType={}", message, messageType); return null; } }) diff --git a/core/src/main/java/bisq/core/payment/PaymentAccount.java b/core/src/main/java/bisq/core/payment/PaymentAccount.java index 2a4b6bd354e..d77c5a9f9ec 100644 --- a/core/src/main/java/bisq/core/payment/PaymentAccount.java +++ b/core/src/main/java/bisq/core/payment/PaymentAccount.java @@ -91,7 +91,7 @@ public protobuf.PaymentAccount toProtoMessage() { .setCreationDate(creationDate) .setPaymentAccountPayload((protobuf.PaymentAccountPayload) paymentAccountPayload.toProtoMessage()) .setAccountName(accountName) - .addAllTradeCurrencies(ProtoUtil.collectionToProto(tradeCurrencies)); + .addAllTradeCurrencies(ProtoUtil.collectionToProto(tradeCurrencies, protobuf.TradeCurrency.class)); Optional.ofNullable(selectedTradeCurrency).ifPresent(selectedTradeCurrency -> builder.setSelectedTradeCurrency((protobuf.TradeCurrency) selectedTradeCurrency.toProtoMessage())); return builder.build(); } diff --git a/core/src/main/java/bisq/core/support/dispute/arbitration/ArbitrationDisputeList.java b/core/src/main/java/bisq/core/support/dispute/arbitration/ArbitrationDisputeList.java index 13f51fecae7..9d625f4a01e 100644 --- a/core/src/main/java/bisq/core/support/dispute/arbitration/ArbitrationDisputeList.java +++ b/core/src/main/java/bisq/core/support/dispute/arbitration/ArbitrationDisputeList.java @@ -74,7 +74,7 @@ public Message toProtoMessage() { list.forEach(dispute -> checkArgument(dispute.getSupportType().equals(SupportType.ARBITRATION), "Support type has to be ARBITRATION")); return protobuf.PersistableEnvelope.newBuilder().setArbitrationDisputeList(protobuf.ArbitrationDisputeList.newBuilder() - .addAllDispute(ProtoUtil.collectionToProto(new ArrayList<>(list)))).build(); + .addAllDispute(ProtoUtil.collectionToProto(new ArrayList<>(list), protobuf.Dispute.class))).build(); } public static ArbitrationDisputeList fromProto(protobuf.ArbitrationDisputeList proto, diff --git a/core/src/main/java/bisq/core/support/dispute/mediation/MediationDisputeList.java b/core/src/main/java/bisq/core/support/dispute/mediation/MediationDisputeList.java index ce45e2fede5..59208c23b7d 100644 --- a/core/src/main/java/bisq/core/support/dispute/mediation/MediationDisputeList.java +++ b/core/src/main/java/bisq/core/support/dispute/mediation/MediationDisputeList.java @@ -67,7 +67,7 @@ private MediationDisputeList(Storage storage, List(list)))).build(); + .addAllDispute(ProtoUtil.collectionToProto(new ArrayList<>(list), protobuf.Dispute.class))).build(); } public static MediationDisputeList fromProto(protobuf.MediationDisputeList proto, diff --git a/core/src/main/java/bisq/core/support/dispute/refund/RefundDisputeList.java b/core/src/main/java/bisq/core/support/dispute/refund/RefundDisputeList.java index f344475560a..6602008a2e6 100644 --- a/core/src/main/java/bisq/core/support/dispute/refund/RefundDisputeList.java +++ b/core/src/main/java/bisq/core/support/dispute/refund/RefundDisputeList.java @@ -74,7 +74,7 @@ public Message toProtoMessage() { list.forEach(dispute -> checkArgument(dispute.getSupportType().equals(SupportType.REFUND), "Support type has to be REFUND")); return protobuf.PersistableEnvelope.newBuilder().setRefundDisputeList(protobuf.RefundDisputeList.newBuilder() - .addAllDispute(ProtoUtil.collectionToProto(new ArrayList<>(list)))).build(); + .addAllDispute(ProtoUtil.collectionToProto(new ArrayList<>(list), protobuf.Dispute.class))).build(); } public static RefundDisputeList fromProto(protobuf.RefundDisputeList proto, diff --git a/core/src/main/java/bisq/core/trade/TradableList.java b/core/src/main/java/bisq/core/trade/TradableList.java index 0c823de42f6..9e0b9cf3b38 100644 --- a/core/src/main/java/bisq/core/trade/TradableList.java +++ b/core/src/main/java/bisq/core/trade/TradableList.java @@ -74,7 +74,7 @@ public Message toProtoMessage() { ArrayList clonedList = new ArrayList<>(this.list); return protobuf.PersistableEnvelope.newBuilder() .setTradableList(protobuf.TradableList.newBuilder() - .addAllTradable(ProtoUtil.collectionToProto(clonedList))) + .addAllTradable(ProtoUtil.collectionToProto(clonedList, protobuf.Tradable.class))) .build(); } diff --git a/core/src/main/java/bisq/core/trade/protocol/ProcessModel.java b/core/src/main/java/bisq/core/trade/protocol/ProcessModel.java index 9e25fa1a0f8..17c6bb76762 100644 --- a/core/src/main/java/bisq/core/trade/protocol/ProcessModel.java +++ b/core/src/main/java/bisq/core/trade/protocol/ProcessModel.java @@ -188,7 +188,8 @@ public protobuf.ProcessModel toProtoMessage() { Optional.ofNullable(takeOfferFeeTxId).ifPresent(builder::setTakeOfferFeeTxId); Optional.ofNullable(payoutTxSignature).ifPresent(e -> builder.setPayoutTxSignature(ByteString.copyFrom(payoutTxSignature))); Optional.ofNullable(preparedDepositTx).ifPresent(e -> builder.setPreparedDepositTx(ByteString.copyFrom(preparedDepositTx))); - Optional.ofNullable(rawTransactionInputs).ifPresent(e -> builder.addAllRawTransactionInputs(ProtoUtil.collectionToProto(rawTransactionInputs))); + Optional.ofNullable(rawTransactionInputs).ifPresent(e -> builder.addAllRawTransactionInputs( + ProtoUtil.collectionToProto(rawTransactionInputs, protobuf.RawTransactionInput.class))); Optional.ofNullable(changeOutputAddress).ifPresent(builder::setChangeOutputAddress); Optional.ofNullable(myMultiSigPubKey).ifPresent(e -> builder.setMyMultiSigPubKey(ByteString.copyFrom(myMultiSigPubKey))); Optional.ofNullable(tempTradingPeerNodeAddress).ifPresent(e -> builder.setTempTradingPeerNodeAddress(tempTradingPeerNodeAddress.toProtoMessage())); diff --git a/core/src/main/java/bisq/core/trade/protocol/TradingPeer.java b/core/src/main/java/bisq/core/trade/protocol/TradingPeer.java index 3a2af777055..5da74be2083 100644 --- a/core/src/main/java/bisq/core/trade/protocol/TradingPeer.java +++ b/core/src/main/java/bisq/core/trade/protocol/TradingPeer.java @@ -104,7 +104,8 @@ public Message toProtoMessage() { Optional.ofNullable(signature).ifPresent(e -> builder.setSignature(ByteString.copyFrom(e))); Optional.ofNullable(pubKeyRing).ifPresent(e -> builder.setPubKeyRing(e.toProtoMessage())); Optional.ofNullable(multiSigPubKey).ifPresent(e -> builder.setMultiSigPubKey(ByteString.copyFrom(e))); - Optional.ofNullable(rawTransactionInputs).ifPresent(e -> builder.addAllRawTransactionInputs(ProtoUtil.collectionToProto(e))); + Optional.ofNullable(rawTransactionInputs).ifPresent(e -> builder.addAllRawTransactionInputs( + ProtoUtil.collectionToProto(e, protobuf.RawTransactionInput.class))); Optional.ofNullable(changeOutputAddress).ifPresent(builder::setChangeOutputAddress); Optional.ofNullable(accountAgeWitnessNonce).ifPresent(e -> builder.setAccountAgeWitnessNonce(ByteString.copyFrom(e))); Optional.ofNullable(accountAgeWitnessSignature).ifPresent(e -> builder.setAccountAgeWitnessSignature(ByteString.copyFrom(e))); diff --git a/core/src/main/java/bisq/core/user/UserPayload.java b/core/src/main/java/bisq/core/user/UserPayload.java index 1edd8f37da3..212570a6f72 100644 --- a/core/src/main/java/bisq/core/user/UserPayload.java +++ b/core/src/main/java/bisq/core/user/UserPayload.java @@ -88,7 +88,7 @@ public protobuf.PersistableEnvelope toProtoMessage() { protobuf.UserPayload.Builder builder = protobuf.UserPayload.newBuilder(); Optional.ofNullable(accountId).ifPresent(e -> builder.setAccountId(accountId)); Optional.ofNullable(paymentAccounts) - .ifPresent(e -> builder.addAllPaymentAccounts(ProtoUtil.collectionToProto(paymentAccounts))); + .ifPresent(e -> builder.addAllPaymentAccounts(ProtoUtil.collectionToProto(paymentAccounts, protobuf.PaymentAccount.class))); Optional.ofNullable(currentPaymentAccount) .ifPresent(e -> builder.setCurrentPaymentAccount(currentPaymentAccount.toProtoMessage())); Optional.ofNullable(acceptedLanguageLocaleCodes) @@ -111,7 +111,7 @@ public protobuf.PersistableEnvelope toProtoMessage() { message -> ((protobuf.StoragePayload) message).getMediator()))); Optional.ofNullable(priceAlertFilter).ifPresent(priceAlertFilter -> builder.setPriceAlertFilter(priceAlertFilter.toProtoMessage())); Optional.ofNullable(marketAlertFilters) - .ifPresent(e -> builder.addAllMarketAlertFilters(ProtoUtil.collectionToProto(marketAlertFilters))); + .ifPresent(e -> builder.addAllMarketAlertFilters(ProtoUtil.collectionToProto(marketAlertFilters, protobuf.MarketAlertFilter.class))); Optional.ofNullable(registeredRefundAgent) .ifPresent(registeredRefundAgent -> builder.setRegisteredRefundAgent(registeredRefundAgent.toProtoMessage().getRefundAgent())); From 09a964ff27574315b3983f9342a02290df16bf50 Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Fri, 15 Nov 2019 17:54:11 +0000 Subject: [PATCH 4/9] Avoid raw types to prevent unchecked casts in Log.java Add missing ILoggingEvent type arg to local variable declarations. --- common/src/main/java/bisq/common/app/Log.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/common/src/main/java/bisq/common/app/Log.java b/common/src/main/java/bisq/common/app/Log.java index bb2268a70d6..ed098d32c9b 100644 --- a/common/src/main/java/bisq/common/app/Log.java +++ b/common/src/main/java/bisq/common/app/Log.java @@ -23,6 +23,7 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; @@ -38,7 +39,7 @@ public static void setLevel(Level logLevel) { public static void setup(String fileName) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - RollingFileAppender appender = new RollingFileAppender(); + RollingFileAppender appender = new RollingFileAppender<>(); appender.setContext(loggerContext); appender.setFile(fileName + ".log"); @@ -50,7 +51,7 @@ public static void setup(String fileName) { rollingPolicy.setMaxIndex(10); rollingPolicy.start(); - SizeBasedTriggeringPolicy triggeringPolicy = new SizeBasedTriggeringPolicy(); + SizeBasedTriggeringPolicy triggeringPolicy = new SizeBasedTriggeringPolicy<>(); triggeringPolicy.setMaxFileSize(FileSize.valueOf("10MB")); triggeringPolicy.start(); @@ -59,15 +60,12 @@ public static void setup(String fileName) { encoder.setPattern("%d{MMM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{15}: %msg %xEx%n"); encoder.start(); - //noinspection unchecked appender.setEncoder(encoder); appender.setRollingPolicy(rollingPolicy); - //noinspection unchecked appender.setTriggeringPolicy(triggeringPolicy); appender.start(); logbackLogger = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); - //noinspection unchecked logbackLogger.addAppender(appender); logbackLogger.setLevel(Level.INFO); From 77a8c20ce90f069cc5e6aa29587ae8bbdc84a410 Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Fri, 15 Nov 2019 22:52:06 +0000 Subject: [PATCH 5/9] Avoid unchecked casts when deserializing JSON using Gson --- .../java/bisq/core/provider/fee/FeeProvider.java | 7 +++---- .../java/bisq/core/provider/price/PriceProvider.java | 12 ++++++------ 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/core/src/main/java/bisq/core/provider/fee/FeeProvider.java b/core/src/main/java/bisq/core/provider/fee/FeeProvider.java index ff7a6f8d642..4cef04ab99f 100644 --- a/core/src/main/java/bisq/core/provider/fee/FeeProvider.java +++ b/core/src/main/java/bisq/core/provider/fee/FeeProvider.java @@ -47,16 +47,15 @@ public FeeProvider(PriceNodeHttpClient httpClient, ProvidersRepository providers public Tuple2, Map> getFees() throws IOException { String json = httpClient.requestWithGET("getFees", "User-Agent", "bisq/" + Version.VERSION + ", uid:" + httpClient.getUid()); - LinkedTreeMap linkedTreeMap = new Gson().>fromJson(json, LinkedTreeMap.class); + LinkedTreeMap linkedTreeMap = new Gson().fromJson(json, LinkedTreeMap.class); Map tsMap = new HashMap<>(); tsMap.put("bitcoinFeesTs", ((Double) linkedTreeMap.get("bitcoinFeesTs")).longValue()); Map map = new HashMap<>(); try { - //noinspection unchecked - LinkedTreeMap dataMap = (LinkedTreeMap) linkedTreeMap.get("dataMap"); - Long btcTxFee = dataMap.get("btcTxFee").longValue(); + LinkedTreeMap dataMap = (LinkedTreeMap) linkedTreeMap.get("dataMap"); + Long btcTxFee = ((Double) dataMap.get("btcTxFee")).longValue(); map.put("BTC", btcTxFee); } catch (Throwable t) { diff --git a/core/src/main/java/bisq/core/provider/price/PriceProvider.java b/core/src/main/java/bisq/core/provider/price/PriceProvider.java index 95f125067e1..78532c728ab 100644 --- a/core/src/main/java/bisq/core/provider/price/PriceProvider.java +++ b/core/src/main/java/bisq/core/provider/price/PriceProvider.java @@ -50,20 +50,20 @@ public Tuple2, Map> getAll() throws IOExc String json = httpClient.requestWithGET("getAllMarketPrices", "User-Agent", "bisq/" + Version.VERSION + ", uid:" + httpClient.getUid()); - LinkedTreeMap map = new Gson().>fromJson(json, LinkedTreeMap.class); + LinkedTreeMap map = new Gson().fromJson(json, LinkedTreeMap.class); Map tsMap = new HashMap<>(); tsMap.put("btcAverageTs", ((Double) map.get("btcAverageTs")).longValue()); tsMap.put("poloniexTs", ((Double) map.get("poloniexTs")).longValue()); tsMap.put("coinmarketcapTs", ((Double) map.get("coinmarketcapTs")).longValue()); - //noinspection unchecked - List> list = (ArrayList>) map.get("data"); - list.forEach(treeMap -> { + List list = (ArrayList) map.get("data"); + list.forEach(obj -> { try { + LinkedTreeMap treeMap = (LinkedTreeMap) obj; final String currencyCode = (String) treeMap.get("currencyCode"); - final double price = (double) treeMap.get("price"); + final double price = (Double) treeMap.get("price"); // json uses double for our timestampSec long value... - final long timestampSec = MathUtils.doubleToLong((double) treeMap.get("timestampSec")); + final long timestampSec = MathUtils.doubleToLong((Double) treeMap.get("timestampSec")); marketPriceMap.put(currencyCode, new MarketPrice(currencyCode, price, timestampSec, true)); } catch (Throwable t) { log.error(t.toString()); From 96ac86dd253290840ac309a898f13abe4c6a2ba5 Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Sat, 16 Nov 2019 00:57:08 +0000 Subject: [PATCH 6/9] Fix unchecked casts in views due to raw chart point types Add missing 'Number' coord type args to some XYChart.(Data|Series) & AreaChart declarations, and avoid passing them as generic varargs, in order to eliminate some more unchecked cast warnings. Also simplify OfferBookChartView.updateChartData() by unboxing the x- coordinate of each (buy & sell) datapoint. --- .../economy/dashboard/BsqDashboardView.java | 6 +- .../main/dao/economy/supply/SupplyView.java | 3 +- .../market/offerbook/OfferBookChartView.java | 65 +++++++++---------- .../offerbook/OfferBookChartViewModel.java | 15 +++-- .../main/market/trades/TradesChartsView.java | 10 ++- 5 files changed, 47 insertions(+), 52 deletions(-) diff --git a/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java b/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java index 1acb91eec94..a13d7ea035e 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java @@ -105,7 +105,7 @@ public class BsqDashboardView extends ActivatableView implements private ChangeListener priceChangeListener; - private AreaChart bsqPriceChart; + private AreaChart bsqPriceChart; private XYChart.Series seriesBSQPrice; private TextField avgPrice90TextField, marketCapTextField, availableAmountTextField; @@ -254,7 +254,7 @@ public Number fromString(String string) { bsqPriceChart.setPrefHeight(bsqPriceChart.getMinHeight()); bsqPriceChart.setCreateSymbols(true); bsqPriceChart.setPadding(new Insets(0)); - bsqPriceChart.getData().addAll(seriesBSQPrice); + bsqPriceChart.getData().add(seriesBSQPrice); AnchorPane chartPane = new AnchorPane(); chartPane.getStyleClass().add("chart-pane"); @@ -368,7 +368,7 @@ private long updateAveragePriceField(TextField textField, int days) { long average = getAverage(bsqTradePast90Days); Coin oneBsq = Coin.valueOf(100); Price avgPrice = Price.valueOf("BSQ", average); - String avg = bsqFormatter.formatPrice(avgPrice); + String avg = BsqFormatter.formatPrice(avgPrice); String bsqInUsdAvg = average > 0 ? GUIUtil.getBsqInUsd(avgPrice, oneBsq, priceFeedService, bsqFormatter) : Res.get("shared.na"); textField.setText(avg + " BSQ/BTC (" + "1 BSQ = " + bsqInUsdAvg + ")"); return average; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/economy/supply/SupplyView.java b/desktop/src/main/java/bisq/desktop/main/dao/economy/supply/SupplyView.java index 6cb4b51519f..84152440351 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/economy/supply/SupplyView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/economy/supply/SupplyView.java @@ -195,7 +195,6 @@ private void createSupplyLockedInformation() { Res.get("dao.factsAndFigures.supply.totalConfiscatedAmount")).second; } - @SuppressWarnings("unchecked") private void createChart(XYChart.Series series, String seriesLabel, String datePattern) { NumberAxis xAxis = new NumberAxis(); xAxis.setForceZeroInRange(false); @@ -246,7 +245,7 @@ public Number fromString(String string) { chart.setPrefHeight(250); chart.setCreateSymbols(true); chart.setPadding(new Insets(0)); - chart.getData().addAll(series); + chart.getData().add(series); AnchorPane chartPane = new AnchorPane(); chartPane.getStyleClass().add("chart-pane"); diff --git a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java index dc8eedf86b7..2b136251029 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java @@ -89,10 +89,8 @@ import javafx.util.StringConverter; import java.util.Collections; -import java.util.Comparator; -import java.util.Optional; +import java.util.List; import java.util.function.Function; -import java.util.function.Supplier; import static bisq.desktop.util.FormBuilder.addTopLabelAutocompleteComboBox; import static bisq.desktop.util.Layout.INITIAL_WINDOW_HEIGHT; @@ -102,7 +100,7 @@ public class OfferBookChartView extends ActivatableViewAndModel seriesBuy, seriesSell; private final Navigation navigation; private final BSFormatter formatter; private TableView buyOfferTableView; @@ -369,7 +367,7 @@ private void createChart() { areaChart.setPrefHeight(270); areaChart.setCreateSymbols(true); areaChart.setPadding(new Insets(0, 10, 0, 10)); - areaChart.getData().addAll(seriesBuy, seriesSell); + areaChart.getData().addAll(List.of(seriesBuy, seriesSell)); chartPane = new AnchorPane(); chartPane.getStyleClass().add("chart-pane"); @@ -387,33 +385,32 @@ private void updateChartData() { seriesSell.getData().clear(); areaChart.getData().clear(); - final Supplier> optionalMaxSupplier = () -> - Optional.of(new XYChart.Data<>(Double.MAX_VALUE, Double.MAX_VALUE)); - - final Optional buyMinOptional = model.getBuyData().stream() - .min(Comparator.comparingDouble(o -> (double) o.getXValue())) - .or(optionalMaxSupplier); - - final Supplier> optionalMinSupplier = () -> - Optional.of(new XYChart.Data<>(Double.MIN_VALUE, Double.MIN_VALUE)); - - // Hide buy offers that are more than a factor 5 higher than the lowest buy offer - final Optional buyMaxOptional = model.getBuyData().stream() - .filter(o -> (double) o.getXValue() < (double) buyMinOptional.get().getXValue() * 3) - .max(Comparator.comparingDouble(o -> (double) o.getXValue())) - .or(optionalMinSupplier); - - final Optional sellMaxOptional = model.getSellData().stream() - .max(Comparator.comparingDouble(o -> (double) o.getXValue())) - .or(optionalMinSupplier); - - final Optional sellMinOptional = model.getSellData().stream() - .filter(o -> (double) o.getXValue() > (double) sellMaxOptional.get().getXValue() / 3) - .min(Comparator.comparingDouble(o -> (double) o.getXValue())) - .or(optionalMaxSupplier); - - final double minValue = Double.min((double) buyMinOptional.get().getXValue(), (double) sellMinOptional.get().getXValue()); - final double maxValue = Double.max((double) buyMaxOptional.get().getXValue(), (double) sellMaxOptional.get().getXValue()); + double buyMinValue = model.getBuyData().stream() + .mapToDouble(o -> o.getXValue().doubleValue()) + .min() + .orElse(Double.MAX_VALUE); + + // Hide buy offers that are more than a factor 3 higher than the lowest buy offer + double buyMaxValue = model.getBuyData().stream() + .mapToDouble(o -> o.getXValue().doubleValue()) + .filter(o -> o < buyMinValue * 3) + .max() + .orElse(Double.MIN_VALUE); + + double sellMaxValue = model.getSellData().stream() + .mapToDouble(o -> o.getXValue().doubleValue()) + .max() + .orElse(Double.MIN_VALUE); + + // Hide sell offers that are less than a factor 3 lower than the highest sell offer + double sellMinValue = model.getSellData().stream() + .mapToDouble(o -> o.getXValue().doubleValue()) + .filter(o -> o > sellMaxValue / 3) + .min() + .orElse(Double.MAX_VALUE); + + double minValue = Double.min(buyMinValue, sellMinValue); + double maxValue = Double.max(buyMaxValue, sellMaxValue); if (minValue == Double.MAX_VALUE || maxValue == Double.MIN_VALUE) { xAxis.setAutoRanging(true); @@ -424,11 +421,9 @@ private void updateChartData() { xAxis.setTickUnit((maxValue - minValue) / 13); } - //noinspection unchecked seriesBuy.getData().addAll(model.getBuyData()); - //noinspection unchecked seriesSell.getData().addAll(model.getSellData()); - areaChart.getData().addAll(seriesBuy, seriesSell); + areaChart.getData().addAll(List.of(seriesBuy, seriesSell)); } private Tuple4, VBox, Button, Label> getOfferTable(OfferPayload.Direction direction) { diff --git a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartViewModel.java b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartViewModel.java index a600e6779df..d70e33235c4 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartViewModel.java @@ -74,8 +74,8 @@ class OfferBookChartViewModel extends ActivatableViewModel { private final Navigation navigation; final ObjectProperty selectedTradeCurrencyProperty = new SimpleObjectProperty<>(); - private final List buyData = new ArrayList<>(); - private final List sellData = new ArrayList<>(); + private final List> buyData = new ArrayList<>(); + private final List> sellData = new ArrayList<>(); private final ObservableList offerBookListItems; private final ListChangeListener offerBookListItemsListener; final CurrencyList currencyListItems; @@ -131,7 +131,7 @@ public OfferBookChartViewModel(OfferBook offerBook, Preferences preferences, Pri fillTradeCurrencies(); }; - currenciesUpdatedListener = new ChangeListener() { + currenciesUpdatedListener = new ChangeListener<>() { @Override public void changed(ObservableValue observable, Number oldValue, Number newValue) { if (!isAnyPricePresent()) { @@ -210,11 +210,11 @@ void setSelectedTabIndex(int selectedTabIndex) { // Getters /////////////////////////////////////////////////////////////////////////////////////////// - public List getBuyData() { + public List> getBuyData() { return buyData; } - public List getSellData() { + public List> getSellData() { return sellData; } @@ -359,7 +359,10 @@ private void updateChartData() { buildChartAndTableEntries(allSellOffers, OfferPayload.Direction.SELL, sellData, topSellOfferList); } - private void buildChartAndTableEntries(List sortedList, OfferPayload.Direction direction, List data, ObservableList offerTableList) { + private void buildChartAndTableEntries(List sortedList, + OfferPayload.Direction direction, + List> data, + ObservableList offerTableList) { data.clear(); double accumulatedAmount = 0; List offerTableListTemp = new ArrayList<>(); diff --git a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java index bc8760f4f34..51f872eaa02 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java @@ -88,6 +88,7 @@ import java.util.Comparator; import java.util.Date; +import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -380,8 +381,7 @@ public Number fromString(String string) { priceChart.setMaxHeight(300); priceChart.setLegendVisible(false); priceChart.setPadding(new Insets(0)); - //noinspection unchecked - priceChart.setData(FXCollections.observableArrayList(priceSeries)); + priceChart.setData(FXCollections.observableArrayList(List.of(priceSeries))); priceChartPane = new AnchorPane(); priceChartPane.getStyleClass().add("chart-pane"); @@ -428,9 +428,8 @@ public Number fromString(String string) { return null; } }); - //noinspection unchecked volumeChart.setId("volume-chart"); - volumeChart.setData(FXCollections.observableArrayList(volumeSeries)); + volumeChart.setData(FXCollections.observableArrayList(List.of(volumeSeries))); volumeChart.setMinHeight(128); volumeChart.setPrefHeight(128); volumeChart.setMaxHeight(200); @@ -457,8 +456,7 @@ private void updateChartData() { priceSeries = new XYChart.Series<>(); priceSeries.getData().setAll(model.priceItems); priceChart.getData().clear(); - //noinspection unchecked - priceChart.setData(FXCollections.observableArrayList(priceSeries)); + priceChart.setData(FXCollections.observableArrayList(List.of(priceSeries))); } private void layoutChart() { From f3456f1920bb115a06ece23abdc3136449894895 Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Sat, 16 Nov 2019 14:09:15 +0000 Subject: [PATCH 7/9] Avoid raw type bounds in class declarations to fix unchecked warnings Make sure the generic classes MutableOfferView & AgentRegistrationView don't use raw bounds for their associated view models, as that leads to unchecked assignments from the model fields further down. --- .../desktop/main/account/register/AgentRegistrationView.java | 4 +++- .../main/java/bisq/desktop/main/offer/MutableOfferView.java | 3 +-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/desktop/src/main/java/bisq/desktop/main/account/register/AgentRegistrationView.java b/desktop/src/main/java/bisq/desktop/main/account/register/AgentRegistrationView.java index 5901ad6f039..d3e4d91be32 100644 --- a/desktop/src/main/java/bisq/desktop/main/account/register/AgentRegistrationView.java +++ b/desktop/src/main/java/bisq/desktop/main/account/register/AgentRegistrationView.java @@ -32,6 +32,7 @@ import bisq.core.app.AppOptionKeys; import bisq.core.locale.LanguageUtil; import bisq.core.locale.Res; +import bisq.core.support.dispute.agent.DisputeAgent; import bisq.common.UserThread; import bisq.common.util.Tuple2; @@ -70,7 +71,8 @@ // TODO translation string keys should renamed to be more generic. // Lets do it for 1.1.7 the translator have time to add new string. @FxmlView -public abstract class AgentRegistrationView extends ActivatableViewAndModel { +public abstract class AgentRegistrationView> + extends ActivatableViewAndModel { private final boolean useDevPrivilegeKeys; private ListView languagesListView; diff --git a/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java b/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java index d4fe7ae23fc..b39c66c3f43 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java @@ -121,7 +121,7 @@ import static bisq.desktop.util.FormBuilder.*; import static javafx.beans.binding.Bindings.createStringBinding; -public abstract class MutableOfferView extends ActivatableViewAndModel { +public abstract class MutableOfferView> extends ActivatableViewAndModel { public static final String BUYER_SECURITY_DEPOSIT_NEWS = "buyerSecurityDepositNews0.9.5"; protected final Navigation navigation; private final Preferences preferences; @@ -438,7 +438,6 @@ private void onShowPayFundsScreen() { balanceTextField.setTargetAmount(model.getDataModel().totalToPayAsCoinProperty().get()); - //noinspection PointlessBooleanExpression if (!DevEnv.isDevMode()) { String key = "securityDepositInfo"; new Popup<>().backgroundInfo(Res.get("popup.info.securityDepositInfo")) From 53b7167e686a679ff3115e7e968e731859d16370 Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Sat, 16 Nov 2019 16:31:55 +0000 Subject: [PATCH 8/9] Fix some remaining suppressed unchecked casts in the UI logic (This still leaves a few more which are hard to avoid.) --- desktop/src/main/java/bisq/desktop/Navigation.java | 8 +++----- .../main/dao/governance/ProposalDisplay.java | 14 +++++--------- .../main/market/trades/TradesChartsView.java | 3 +-- .../src/main/java/bisq/desktop/util/GUIUtil.java | 6 +----- 4 files changed, 10 insertions(+), 21 deletions(-) diff --git a/desktop/src/main/java/bisq/desktop/Navigation.java b/desktop/src/main/java/bisq/desktop/Navigation.java index a5f82fc52d2..020b0720a48 100644 --- a/desktop/src/main/java/bisq/desktop/Navigation.java +++ b/desktop/src/main/java/bisq/desktop/Navigation.java @@ -84,8 +84,7 @@ public void readPersisted() { List> viewClasses = persisted.getPath().stream() .map(className -> { try { - //noinspection unchecked - return ((Class) Class.forName(className)); + return (Class) Class.forName(className).asSubclass(View.class); } catch (ClassNotFoundException e) { log.warn("Could not find the viewPath class {}; exception: {}", className, e); } @@ -118,13 +117,12 @@ public void navigateTo(ViewPath newPath, @Nullable Object data) { Class viewClass = newPath.get(i); temp.add(viewClass); if (currentPath == null || - (currentPath != null && - currentPath.size() > i && + (currentPath.size() > i && viewClass != currentPath.get(i) && i != newPath.size() - 1)) { ArrayList> temp2 = new ArrayList<>(temp); for (int n = i + 1; n < newPath.size(); n++) { - //noinspection unchecked,unchecked,unchecked + //noinspection unchecked Class[] newTemp = new Class[i + 1]; currentPath = ViewPath.to(temp2.toArray(newTemp)); navigateTo(currentPath, data); diff --git a/desktop/src/main/java/bisq/desktop/main/dao/governance/ProposalDisplay.java b/desktop/src/main/java/bisq/desktop/main/dao/governance/ProposalDisplay.java index 203fa4d1929..5eabf28ac21 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/governance/ProposalDisplay.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/governance/ProposalDisplay.java @@ -136,7 +136,7 @@ public class ProposalDisplay { @Getter private List inputControls = new ArrayList<>(); @Getter - private List comboBoxes = new ArrayList<>(); + private List> comboBoxes = new ArrayList<>(); private final ChangeListener focusOutListener; private final ChangeListener inputListener; private ChangeListener paramChangeListener; @@ -602,10 +602,8 @@ private void addListeners() { inputControl.focusedProperty().addListener(focusOutListener); }); comboBoxes.stream() - .filter(Objects::nonNull).forEach(comboBox -> { - //noinspection unchecked - comboBox.getSelectionModel().selectedItemProperty().addListener(inputListener); - }); + .filter(Objects::nonNull) + .forEach(comboBox -> comboBox.getSelectionModel().selectedItemProperty().addListener(inputListener)); } public void removeListeners() { @@ -615,10 +613,8 @@ public void removeListeners() { inputControl.focusedProperty().removeListener(focusOutListener); }); comboBoxes.stream() - .filter(Objects::nonNull).forEach(comboBox -> { - //noinspection unchecked - comboBox.getSelectionModel().selectedItemProperty().removeListener(inputListener); - }); + .filter(Objects::nonNull) + .forEach(comboBox -> comboBox.getSelectionModel().selectedItemProperty().removeListener(inputListener)); if (paramComboBox != null && paramChangeListener != null) paramComboBox.getSelectionModel().selectedItemProperty().removeListener(paramChangeListener); diff --git a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java index 51f872eaa02..c2994b19eb5 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java @@ -89,7 +89,6 @@ import java.util.Comparator; import java.util.Date; import java.util.List; -import java.util.Objects; import java.util.concurrent.TimeUnit; import org.jetbrains.annotations.NotNull; @@ -185,7 +184,7 @@ public void initialize() { @Override protected void activate() { // root.getParent() is null at initialize - tabPaneSelectionModel = Objects.requireNonNull(GUIUtil.getParentOfType(root, JFXTabPane.class)).getSelectionModel(); + tabPaneSelectionModel = GUIUtil.getParentOfType(root, JFXTabPane.class).getSelectionModel(); selectedTabIndexListener = (observable, oldValue, newValue) -> model.setSelectedTabIndex((int) newValue); model.setSelectedTabIndex(tabPaneSelectionModel.getSelectedIndex()); tabPaneSelectionModel.selectedIndexProperty().addListener(selectedTabIndexListener); diff --git a/desktop/src/main/java/bisq/desktop/util/GUIUtil.java b/desktop/src/main/java/bisq/desktop/util/GUIUtil.java index 0add2cfa429..4491d3e22a6 100644 --- a/desktop/src/main/java/bisq/desktop/util/GUIUtil.java +++ b/desktop/src/main/java/bisq/desktop/util/GUIUtil.java @@ -188,11 +188,8 @@ public static void focusWhenAddedToScene(Node node) { }); } - @SuppressWarnings("PointlessBooleanExpression") public static void showFeeInfoBeforeExecute(Runnable runnable) { - //noinspection UnusedAssignment String key = "miningFeeInfo"; - //noinspection ConstantConditions,ConstantConditions if (!DevEnv.isDevMode() && DontShowAgainLookup.showAgain(key)) { new Popup<>().attention(Res.get("guiUtil.miningFeeInfo", String.valueOf(GUIUtil.feeService.getTxFeePerByte().value))) .onClose(runnable) @@ -682,8 +679,7 @@ public static T getParentOfType(Node node, Class t) { parent = parent.getParent(); } } - //noinspection unchecked - return parent != null ? (T) parent : null; + return t.cast(parent); } public static void showClearXchangeWarning() { From 5e69073280556248f39b40f181dd6b3a1dcaf5fe Mon Sep 17 00:00:00 2001 From: Steven Barclay Date: Sat, 16 Nov 2019 17:41:55 +0000 Subject: [PATCH 9/9] Fix a few remaining unsuppressed unchecked warnings --- .../java/bisq/core/app/BisqEnvironment.java | 4 ++-- .../java/bisq/core/btc/setup/WalletConfig.java | 4 ++-- .../components/AutocompleteComboBox.java | 4 ++-- .../components/paymentmethods/AssetsForm.java | 11 ++++++----- .../paymentmethods/JapanBankTransferForm.java | 4 ++-- .../bisq/monitor/metric/P2PMarketStats.java | 6 +++--- .../monitor/metric/P2PSeedNodeSnapshot.java | 18 +++++++++--------- .../metric/P2PSeedNodeSnapshotBase.java | 2 +- 8 files changed, 27 insertions(+), 26 deletions(-) diff --git a/core/src/main/java/bisq/core/app/BisqEnvironment.java b/core/src/main/java/bisq/core/app/BisqEnvironment.java index ca8415c2d69..ddebb407ae1 100644 --- a/core/src/main/java/bisq/core/app/BisqEnvironment.java +++ b/core/src/main/java/bisq/core/app/BisqEnvironment.java @@ -361,11 +361,11 @@ PropertySource getAppDirProperties() throws Exception { return new ResourcePropertySource(BISQ_APP_DIR_PROPERTY_SOURCE_NAME, resource); } - private String getProperty (PropertySource properties, String propertyKey, String defaultValue) { + private String getProperty(PropertySource properties, String propertyKey, String defaultValue) { return properties.containsProperty(propertyKey) ? (String) properties.getProperty(propertyKey) : defaultValue; } - private List getListProperty (String key, List defaultValue) { + private List getListProperty(String key, List defaultValue) { final String value = getProperty(key, ""); return value.isEmpty() ? defaultValue : Arrays.asList(StringUtils.deleteWhitespace(value).split(",")); } diff --git a/core/src/main/java/bisq/core/btc/setup/WalletConfig.java b/core/src/main/java/bisq/core/btc/setup/WalletConfig.java index 0a74eef93ed..85bcdebed93 100644 --- a/core/src/main/java/bisq/core/btc/setup/WalletConfig.java +++ b/core/src/main/java/bisq/core/btc/setup/WalletConfig.java @@ -55,6 +55,7 @@ import com.google.common.util.concurrent.AbstractIdleService; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -465,7 +466,7 @@ protected void startUp() throws Exception { vPeerGroup.startBlockChainDownload(listener); listener.await(); } else { - Futures.addCallback(vPeerGroup.startAsync(), new FutureCallback() { + Futures.addCallback((ListenableFuture) vPeerGroup.startAsync(), new FutureCallback() { @Override public void onSuccess(@Nullable Object result) { final PeerDataEventListener listener = downloadListener == null ? @@ -476,7 +477,6 @@ public void onSuccess(@Nullable Object result) { @Override public void onFailure(@NotNull Throwable t) { throw new RuntimeException(t); - } }); } diff --git a/desktop/src/main/java/bisq/desktop/components/AutocompleteComboBox.java b/desktop/src/main/java/bisq/desktop/components/AutocompleteComboBox.java index 1127862f2b8..716f81dc0c9 100644 --- a/desktop/src/main/java/bisq/desktop/components/AutocompleteComboBox.java +++ b/desktop/src/main/java/bisq/desktop/components/AutocompleteComboBox.java @@ -46,7 +46,7 @@ public class AutocompleteComboBox extends JFXComboBox { private ArrayList completeList; private ArrayList matchingList; - private JFXComboBoxListViewSkin comboBoxListViewSkin; + private JFXComboBoxListViewSkin comboBoxListViewSkin; public AutocompleteComboBox() { this(FXCollections.observableArrayList()); @@ -65,7 +65,7 @@ private AutocompleteComboBox(ObservableList items) { /** * Set the complete list of ComboBox items. Use this instead of setItems(). */ - public void setAutocompleteItems(List items) { + public void setAutocompleteItems(List items) { completeList = new ArrayList<>(items); matchingList = new ArrayList<>(completeList); setValue(null); diff --git a/desktop/src/main/java/bisq/desktop/components/paymentmethods/AssetsForm.java b/desktop/src/main/java/bisq/desktop/components/paymentmethods/AssetsForm.java index 6ddde755889..9eb967bf738 100644 --- a/desktop/src/main/java/bisq/desktop/components/paymentmethods/AssetsForm.java +++ b/desktop/src/main/java/bisq/desktop/components/paymentmethods/AssetsForm.java @@ -211,10 +211,11 @@ protected void addTradeCurrencyComboBox() { currencyComboBox.setPromptText(""); }); - ((AutocompleteComboBox) currencyComboBox).setAutocompleteItems(CurrencyUtil.getActiveSortedCryptoCurrencies(assetService, filterManager)); + ((AutocompleteComboBox) currencyComboBox).setAutocompleteItems( + CurrencyUtil.getActiveSortedCryptoCurrencies(assetService, filterManager)); currencyComboBox.setVisibleRowCount(Math.min(currencyComboBox.getItems().size(), 10)); - currencyComboBox.setConverter(new StringConverter() { + currencyComboBox.setConverter(new StringConverter<>() { @Override public String toString(TradeCurrency tradeCurrency) { return tradeCurrency != null ? tradeCurrency.getNameAndCode() : ""; @@ -223,12 +224,12 @@ public String toString(TradeCurrency tradeCurrency) { @Override public TradeCurrency fromString(String s) { return currencyComboBox.getItems().stream(). - filter(item -> item.getNameAndCode().equals(s)). - findAny().orElse(null); + filter(item -> item.getNameAndCode().equals(s)). + findAny().orElse(null); } }); - ((AutocompleteComboBox) currencyComboBox).setOnChangeConfirmed(e -> { + ((AutocompleteComboBox) currencyComboBox).setOnChangeConfirmed(e -> { addressInputTextField.resetValidation(); addressInputTextField.validate(); paymentAccount.setSingleTradeCurrency(currencyComboBox.getSelectionModel().getSelectedItem()); diff --git a/desktop/src/main/java/bisq/desktop/components/paymentmethods/JapanBankTransferForm.java b/desktop/src/main/java/bisq/desktop/components/paymentmethods/JapanBankTransferForm.java index a6535a3a65b..6d9dd140c4a 100644 --- a/desktop/src/main/java/bisq/desktop/components/paymentmethods/JapanBankTransferForm.java +++ b/desktop/src/main/java/bisq/desktop/components/paymentmethods/JapanBankTransferForm.java @@ -197,12 +197,12 @@ public String fromString(String s) { return s != null ? s : ""; } }); - ((AutocompleteComboBox) bankComboBox).setAutocompleteItems(JapanBankData.prettyPrintBankList()); + ((AutocompleteComboBox) bankComboBox).setAutocompleteItems(JapanBankData.prettyPrintBankList()); bankComboBox.setPrefWidth(430); bankComboBox.setVisibleRowCount(430); - ((AutocompleteComboBox) bankComboBox).setOnChangeConfirmed(e -> { + ((AutocompleteComboBox) bankComboBox).setOnChangeConfirmed(e -> { // get selected value String bank = bankComboBox.getSelectionModel().getSelectedItem(); diff --git a/monitor/src/main/java/bisq/monitor/metric/P2PMarketStats.java b/monitor/src/main/java/bisq/monitor/metric/P2PMarketStats.java index 2073fd7741f..edebbf13d44 100644 --- a/monitor/src/main/java/bisq/monitor/metric/P2PMarketStats.java +++ b/monitor/src/main/java/bisq/monitor/metric/P2PMarketStats.java @@ -68,7 +68,7 @@ public class P2PMarketStats extends P2PSeedNodeSnapshotBase { private final Set hashes = new TreeSet<>(Arrays::compare); - final Map versionBucketsPerHost = new ConcurrentHashMap<>(); + final Map> versionBucketsPerHost = new ConcurrentHashMap<>(); /** * Efficient way to count occurrences. @@ -189,13 +189,13 @@ protected List getRequests() { @Override protected void report() { Map report = new HashMap<>(); - bucketsPerHost.forEach((host, statistics) -> statistics.values().forEach((market, numberOfOffers) -> report.put(OnionParser.prettyPrint(host) + "." + market.toString(), String.valueOf(((Counter) numberOfOffers).value())))); + bucketsPerHost.forEach((host, statistics) -> statistics.values().forEach((market, numberOfOffers) -> report.put(OnionParser.prettyPrint(host) + "." + market, String.valueOf(((Counter) numberOfOffers).value())))); reporter.report(report, getName()); // do version statistics report.clear(); - versionBucketsPerHost.values().stream().findAny().get().values().forEach((version, numberOfOccurrences) -> report.put(version.toString(), String.valueOf(((Counter) numberOfOccurrences).value()))); + versionBucketsPerHost.values().stream().findAny().get().values().forEach((version, numberOfOccurrences) -> report.put(version, String.valueOf(numberOfOccurrences.value()))); reporter.report(report, "versions"); } diff --git a/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshot.java b/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshot.java index f7f28b392a0..77462aa4e5e 100644 --- a/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshot.java +++ b/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshot.java @@ -84,7 +84,7 @@ public class P2PSeedNodeSnapshot extends P2PSeedNodeSnapshotBase { private static final String DATABASE_DIR = "run.dbDir"; Statistics statistics; - final Map bucketsPerHost = new ConcurrentHashMap<>(); + final Map>> bucketsPerHost = new ConcurrentHashMap<>(); protected final Set hashes = new TreeSet<>(Arrays::compare); private int daostateheight = 594000; private int proposalheight = daostateheight; @@ -174,19 +174,19 @@ void report() { Map report = new HashMap<>(); // - assemble histograms bucketsPerHost.forEach((host, statistics) -> statistics.values().forEach((type, set) -> report - .put(OnionParser.prettyPrint(host) + ".numberOfMessages." + type, Integer.toString(((Set) set).size())))); + .put(OnionParser.prettyPrint(host) + ".numberOfMessages." + type, Integer.toString(set.size())))); // - assemble diffs // - transfer values - Map messagesPerHost = new HashMap<>(); + Map>> messagesPerHost = new HashMap<>(); bucketsPerHost.forEach((host, value) -> messagesPerHost.put(OnionParser.prettyPrint(host), value)); // - pick reference seed node and its values String referenceHost = "overall_number_of_unique_messages"; Map> referenceValues = new HashMap<>(); messagesPerHost.forEach((host, statistics) -> statistics.values().forEach((type, set) -> { - referenceValues.putIfAbsent((String) type, new HashSet<>()); - referenceValues.get(type).addAll((Set) set); + referenceValues.putIfAbsent(type, new HashSet<>()); + referenceValues.get(type).addAll(set); })); // - calculate diffs @@ -195,7 +195,7 @@ void report() { statistics.values().forEach((messageType, set) -> { try { report.put(OnionParser.prettyPrint(host) + ".relativeNumberOfMessages." + messageType, - String.valueOf(((Set) set).size() - referenceValues.get(messageType).size())); + String.valueOf(set.size() - referenceValues.get(messageType).size())); } catch (MalformedURLException | NullPointerException ignore) { log.error("we should never have gotten here", ignore); } @@ -223,8 +223,8 @@ void report() { // - transcode Map> perType = new HashMap<>(); daoData.forEach((nodeAddress, daostatistics) -> daostatistics.values().forEach((type, tuple) -> { - perType.putIfAbsent((String) type, new HashMap<>()); - perType.get(type).put(nodeAddress, (Tuple) tuple); + perType.putIfAbsent(type, new HashMap<>()); + perType.get(type).put(nodeAddress, tuple); })); // - process dao data @@ -311,7 +311,7 @@ public void reset() { } } - private Map daoData = new ConcurrentHashMap<>(); + private Map> daoData = new ConcurrentHashMap<>(); protected boolean treatMessage(NetworkEnvelope networkEnvelope, Connection connection) { checkNotNull(connection.getPeersNodeAddressProperty(), diff --git a/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshotBase.java b/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshotBase.java index 2b7fb9097b3..567bcff8f9f 100644 --- a/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshotBase.java +++ b/monitor/src/main/java/bisq/monitor/metric/P2PSeedNodeSnapshotBase.java @@ -63,7 +63,7 @@ public abstract class P2PSeedNodeSnapshotBase extends Metric implements MessageL private static final String HOSTS = "run.hosts"; private static final String TOR_PROXY_PORT = "run.torProxyPort"; Statistics statistics; - final Map bucketsPerHost = new ConcurrentHashMap<>(); + final Map> bucketsPerHost = new ConcurrentHashMap<>(); private final ThreadGate gate = new ThreadGate(); /**