diff --git a/src/main/java/io/bitsquare/BitSquare.java b/src/main/java/io/bitsquare/BitSquare.java index 5caba3bff3..10c5f5c081 100644 --- a/src/main/java/io/bitsquare/BitSquare.java +++ b/src/main/java/io/bitsquare/BitSquare.java @@ -70,8 +70,8 @@ public class BitSquare extends Application final User user = injector.getInstance(User.class); final Settings settings = injector.getInstance(Settings.class); final Storage storage = injector.getInstance(Storage.class); + storage.init(); user.updateFromStorage((User) storage.read(user.getClass().getName())); - settings.updateFromStorage((Settings) storage.read(settings.getClass().getName())); if (ID.isEmpty()) @@ -88,9 +88,9 @@ public class BitSquare extends Application try { - final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(NavigationItem.MAIN.getFxmlUrl()), Localisation.getResourceBundle()); + @NotNull final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(NavigationItem.MAIN.getFxmlUrl()), Localisation.getResourceBundle()); final Parent mainView = loader.load(); - final Scene scene = new Scene(mainView, 800, 600); + @NotNull final Scene scene = new Scene(mainView, 800, 600); stage.setScene(scene); final String bitsquare = getClass().getResource("/io/bitsquare/gui/bitsquare.css").toExternalForm(); diff --git a/src/main/java/io/bitsquare/RelayNode.java b/src/main/java/io/bitsquare/RelayNode.java index 3a06877cca..43448fc5cd 100755 --- a/src/main/java/io/bitsquare/RelayNode.java +++ b/src/main/java/io/bitsquare/RelayNode.java @@ -3,24 +3,26 @@ package io.bitsquare; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerMaker; import net.tomp2p.peers.Number160; +import org.jetbrains.annotations.Nullable; /** * Network node for relaying p2p msg */ -public class RelayNode +class RelayNode { - public static final Number160 ID = Number160.createHash(1); + private static final Number160 ID = Number160.createHash(1); + @Nullable private static Peer masterPeer = null; - public static void main(String[] args) throws Exception + public static void main(@Nullable String[] args) throws Exception { - if (args.length == 1) + if (args != null && args.length == 1) INSTANCE(new Integer(args[0])); else INSTANCE(5000); } - public static Peer INSTANCE(int port) throws Exception + private static void INSTANCE(int port) throws Exception { if (masterPeer == null) { @@ -28,6 +30,5 @@ public class RelayNode // masterPeer = new PeerMaker(ID).setPorts(port).setBagSize(100).makeAndListen(); // setBagSize cause sync problems... masterPeer.getBroadcastRPC().getConnectionBean().getConnectionReservation().reserve(3).awaitUninterruptibly(); } - return masterPeer; } } diff --git a/src/main/java/io/bitsquare/bank/BankAccount.java b/src/main/java/io/bitsquare/bank/BankAccount.java index 2ef8db18b8..2744dfbbac 100644 --- a/src/main/java/io/bitsquare/bank/BankAccount.java +++ b/src/main/java/io/bitsquare/bank/BankAccount.java @@ -4,29 +4,39 @@ import io.bitsquare.locale.Country; import java.io.Serializable; import java.util.Currency; import java.util.Objects; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class BankAccount implements Serializable { private static final long serialVersionUID = 1792577576443221268L; - private final BankAccountTypeInfo bankAccountTypeInfo; + @NotNull + private final BankAccountType bankAccountType; + @NotNull private final String accountPrimaryID; + @NotNull private final String accountSecondaryID; + @NotNull private final String accountHolderName; + @NotNull private final Country country; + @NotNull private final Currency currency; + @NotNull private final String uid; + @NotNull private final String accountTitle; - public BankAccount(BankAccountTypeInfo bankAccountTypeInfo, - Currency currency, - Country country, - String accountTitle, - String accountHolderName, - String accountPrimaryID, - String accountSecondaryID) + public BankAccount(@NotNull BankAccountType bankAccountType, + @NotNull Currency currency, + @NotNull Country country, + @NotNull String accountTitle, + @NotNull String accountHolderName, + @NotNull String accountPrimaryID, + @NotNull String accountSecondaryID) { - this.bankAccountTypeInfo = bankAccountTypeInfo; + this.bankAccountType = bankAccountType; this.currency = currency; this.country = country; this.accountTitle = accountTitle; @@ -42,62 +52,71 @@ public class BankAccount implements Serializable return Objects.hashCode(uid); } - public boolean equals(Object obj) + public boolean equals(@Nullable Object obj) { if (!(obj instanceof BankAccount)) return false; if (obj == this) return true; - BankAccount other = (BankAccount) obj; - return other.getUid().equals(uid); + final BankAccount other = (BankAccount) obj; + return uid.equals(other.getUid()); } + @NotNull public String getAccountPrimaryID() { return accountPrimaryID; } + @NotNull public String getAccountSecondaryID() { return accountSecondaryID; } + @NotNull public String getAccountHolderName() { return accountHolderName; } - public BankAccountTypeInfo getBankAccountTypeInfo() + @NotNull + public BankAccountType getBankAccountType() { - return bankAccountTypeInfo; + return bankAccountType; } + @NotNull public Currency getCurrency() { return currency; } + @NotNull public Country getCountry() { return country; } + @NotNull public String getUid() { return uid; } + @NotNull public String getAccountTitle() { return accountTitle; } + @NotNull @Override public String toString() { return "BankAccount{" + - "bankAccountType=" + bankAccountTypeInfo.getType() + + "bankAccountType=" + bankAccountType + ", accountPrimaryID='" + accountPrimaryID + '\'' + ", accountSecondaryID='" + accountSecondaryID + '\'' + ", accountHolderName='" + accountHolderName + '\'' + diff --git a/src/main/java/io/bitsquare/bank/BankAccountType.java b/src/main/java/io/bitsquare/bank/BankAccountType.java new file mode 100644 index 0000000000..7f9235675b --- /dev/null +++ b/src/main/java/io/bitsquare/bank/BankAccountType.java @@ -0,0 +1,45 @@ +package io.bitsquare.bank; + +import java.util.ArrayList; +import java.util.Arrays; +import org.jetbrains.annotations.NotNull; + +public enum BankAccountType +{ + SEPA("IBAN", "BIC"), + WIRE("primary ID", "secondary ID"), + INTERNATIONAL("primary ID", "secondary ID"), + OK_PAY("primary ID", "secondary ID"), + NET_TELLER("primary ID", "secondary ID"), + PERFECT_MONEY("primary ID", "secondary ID"), + OTHER("primary ID", "secondary ID"); + + @NotNull + private final String primaryId; + @NotNull + private final String secondaryId; + + BankAccountType(@NotNull String primaryId, @NotNull String secondaryId) + { + this.primaryId = primaryId; + this.secondaryId = secondaryId; + } + + @NotNull + public static ArrayList getAllBankAccountTypes() + { + return new ArrayList<>(Arrays.asList(BankAccountType.values())); + } + + @NotNull + public String getPrimaryId() + { + return primaryId; + } + + @NotNull + public String getSecondaryId() + { + return secondaryId; + } +} diff --git a/src/main/java/io/bitsquare/bank/BankAccountTypeInfo.java b/src/main/java/io/bitsquare/bank/BankAccountTypeInfo.java deleted file mode 100644 index 0106ad323c..0000000000 --- a/src/main/java/io/bitsquare/bank/BankAccountTypeInfo.java +++ /dev/null @@ -1,69 +0,0 @@ -package io.bitsquare.bank; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Objects; - -public class BankAccountTypeInfo implements Serializable -{ - private static final long serialVersionUID = -8772708150197835288L; - private final BankAccountType type; - private final String primaryIDName; - private final String secondaryIDName; - - public BankAccountTypeInfo(BankAccountType type, String primaryIDName, String secondaryIDName) - { - this.type = type; - this.primaryIDName = primaryIDName; - this.secondaryIDName = secondaryIDName; - } - - public static ArrayList getAllBankAccountTypeInfoObjects() - { - ArrayList bankTransferTypes = new ArrayList<>(); - bankTransferTypes.add(new BankAccountTypeInfo(BankAccountType.SEPA, "IBAN", "BIC")); - bankTransferTypes.add(new BankAccountTypeInfo(BankAccountType.WIRE, "Prim_todo", "Sec_todo")); - bankTransferTypes.add(new BankAccountTypeInfo(BankAccountType.INTERNATIONAL, "Prim_todo", "Sec_todo")); - bankTransferTypes.add(new BankAccountTypeInfo(BankAccountType.OK_PAY, "Prim_todo", "Sec_todo")); - bankTransferTypes.add(new BankAccountTypeInfo(BankAccountType.NET_TELLER, "Prim_todo", "Sec_todo")); - bankTransferTypes.add(new BankAccountTypeInfo(BankAccountType.PERFECT_MONEY, "Prim_todo", "Sec_todo")); - bankTransferTypes.add(new BankAccountTypeInfo(BankAccountType.OTHER, "Prim_todo", "Sec_todo")); - return bankTransferTypes; - } - - public int hashCode() - { - return Objects.hashCode(type); - } - - public boolean equals(Object obj) - { - if (!(obj instanceof BankAccountTypeInfo)) - return false; - if (obj == this) - return true; - - BankAccountTypeInfo other = (BankAccountTypeInfo) obj; - return other.getType().equals(type); - } - - public BankAccountType getType() - { - return type; - } - - public String getPrimaryIDName() - { - return primaryIDName; - } - - public String getSecondaryIDName() - { - return secondaryIDName; - } - - public static enum BankAccountType - { - SEPA, WIRE, INTERNATIONAL, OK_PAY, NET_TELLER, PERFECT_MONEY, OTHER - } -} diff --git a/src/main/java/io/bitsquare/btc/AddressBasedCoinSelector.java b/src/main/java/io/bitsquare/btc/AddressBasedCoinSelector.java index 339bc51382..805f9f19fb 100644 --- a/src/main/java/io/bitsquare/btc/AddressBasedCoinSelector.java +++ b/src/main/java/io/bitsquare/btc/AddressBasedCoinSelector.java @@ -10,6 +10,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,7 +19,7 @@ import org.slf4j.LoggerFactory; * possible. This means that the transaction is the most likely to get confirmed. Note that this means we may end up * "spending" more priority than would be required to get the transaction we are creating confirmed. */ -public class AddressBasedCoinSelector extends DefaultCoinSelector +class AddressBasedCoinSelector extends DefaultCoinSelector { private static final Logger log = LoggerFactory.getLogger(AddressBasedCoinSelector.class); private final NetworkParameters params; @@ -41,8 +42,9 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector this.includePending = includePending; } + @SuppressWarnings("WeakerAccess") @VisibleForTesting - static void sortOutputs(ArrayList outputs) + static void sortOutputs(@NotNull ArrayList outputs) { Collections.sort(outputs, (a, b) -> { int depth1 = 0; @@ -69,7 +71,7 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector }); } - private static boolean isInBlockChainOrPending(Transaction tx) + private static boolean isInBlockChainOrPending(@NotNull Transaction tx) { // Pick chain-included transactions and transactions that are pending. TransactionConfidence confidence = tx.getConfidence(); @@ -81,7 +83,7 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector (confidence.numBroadcastPeers() > 1 || tx.getParams() == RegTestParams.get()); } - private static boolean isInBlockChain(Transaction tx) + private static boolean isInBlockChain(@NotNull Transaction tx) { // Only pick chain-included transactions. TransactionConfidence confidence = tx.getConfidence(); @@ -92,7 +94,7 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector /** * Sub-classes can override this to just customize whether transactions are usable, but keep age sorting. */ - protected boolean shouldSelect(Transaction tx) + protected boolean shouldSelect(@NotNull Transaction tx) { if (includePending) return isInBlockChainOrPending(tx); @@ -100,7 +102,8 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector return isInBlockChain(tx); } - protected boolean matchesRequiredAddress(TransactionOutput transactionOutput) + @SuppressWarnings("WeakerAccess") + protected boolean matchesRequiredAddress(@NotNull TransactionOutput transactionOutput) { if (transactionOutput.getScriptPubKey().isSentToAddress() || transactionOutput.getScriptPubKey().isSentToP2SH()) { @@ -113,13 +116,14 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector return false; } - public CoinSelection select(BigInteger biTarget, LinkedList candidates) + @NotNull + public CoinSelection select(@NotNull BigInteger biTarget, @NotNull LinkedList candidates) { long target = biTarget.longValue(); - HashSet selected = new HashSet<>(); + @NotNull HashSet selected = new HashSet<>(); // Sort the inputs by age*value so we get the highest "coindays" spent. // TODO: Consider changing the wallets internal format to track just outputs and keep them ordered. - ArrayList sortedOutputs = new ArrayList<>(candidates); + @NotNull ArrayList sortedOutputs = new ArrayList<>(candidates); // When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting // them in order to improve performance. if (!biTarget.equals(NetworkParameters.MAX_MONEY)) @@ -129,7 +133,7 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector // Now iterate over the sorted outputs until we have got as close to the target as possible or a little // bit over (excessive value will be change). long total = 0; - for (TransactionOutput output : sortedOutputs) + for (@NotNull TransactionOutput output : sortedOutputs) { if (total >= target) break; // Only pick chain-included transactions, or transactions that are ours and pending. diff --git a/src/main/java/io/bitsquare/btc/AddressEntry.java b/src/main/java/io/bitsquare/btc/AddressEntry.java index a88d1f9c8e..55f2eadb8c 100644 --- a/src/main/java/io/bitsquare/btc/AddressEntry.java +++ b/src/main/java/io/bitsquare/btc/AddressEntry.java @@ -5,6 +5,7 @@ import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.Utils; import java.io.Serializable; +import org.jetbrains.annotations.Nullable; public class AddressEntry implements Serializable { @@ -12,6 +13,7 @@ public class AddressEntry implements Serializable private final ECKey key; private final NetworkParameters params; private final AddressContext addressContext; + @Nullable private String tradeId = null; public AddressEntry(ECKey key, NetworkParameters params, AddressContext addressContext) @@ -21,12 +23,13 @@ public class AddressEntry implements Serializable this.addressContext = addressContext; } + @Nullable public String getTradeId() { return tradeId; } - public void setTradeId(String tradeId) + public void setTradeId(@Nullable String tradeId) { this.tradeId = tradeId; } diff --git a/src/main/java/io/bitsquare/btc/BitSquareWallet.java b/src/main/java/io/bitsquare/btc/BitSquareWallet.java index dfda4a0bfc..9f35712e2e 100644 --- a/src/main/java/io/bitsquare/btc/BitSquareWallet.java +++ b/src/main/java/io/bitsquare/btc/BitSquareWallet.java @@ -7,7 +7,7 @@ import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class BitSquareWallet extends Wallet implements Serializable +class BitSquareWallet extends Wallet implements Serializable { private static final Logger log = LoggerFactory.getLogger(BitSquareWallet.class); private static final long serialVersionUID = -6231929674475881549L; @@ -17,7 +17,7 @@ public class BitSquareWallet extends Wallet implements Serializable super(params); } - public BitSquareWallet(NetworkParameters params, KeyCrypter keyCrypter) + private BitSquareWallet(NetworkParameters params, KeyCrypter keyCrypter) { super(params, keyCrypter); } diff --git a/src/main/java/io/bitsquare/btc/BitSquareWalletAppKit.java b/src/main/java/io/bitsquare/btc/BitSquareWalletAppKit.java index e69ea1d597..1597c872ae 100644 --- a/src/main/java/io/bitsquare/btc/BitSquareWalletAppKit.java +++ b/src/main/java/io/bitsquare/btc/BitSquareWalletAppKit.java @@ -12,13 +12,15 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class BitSquareWalletAppKit extends WalletAppKit { - public BitSquareWalletAppKit(NetworkParameters params, File directory, String filePrefix) + public BitSquareWalletAppKit(NetworkParameters params, File directory) { - super(params, directory, filePrefix); + super(params, directory, WalletFacade.WALLET_PREFIX); } @Override @@ -32,10 +34,10 @@ public class BitSquareWalletAppKit extends WalletAppKit throw new IOException("Could not create named directory."); } } - FileInputStream walletStream = null; + @Nullable FileInputStream walletStream = null; try { - File chainFile = new File(directory, filePrefix + ".spvchain"); + @NotNull File chainFile = new File(directory, filePrefix + ".spvchain"); boolean chainFileExists = chainFile.exists(); vWalletFile = new File(directory, filePrefix + ".wallet"); boolean shouldReplayWallet = vWalletFile.exists() && !chainFileExists; @@ -50,8 +52,8 @@ public class BitSquareWalletAppKit extends WalletAppKit long time = Long.MAX_VALUE; if (vWalletFile.exists()) { - Wallet wallet = new BitSquareWallet(params); - FileInputStream stream = new FileInputStream(vWalletFile); + @NotNull Wallet wallet = new BitSquareWallet(params); + @NotNull FileInputStream stream = new FileInputStream(vWalletFile); new WalletProtobufSerializer().readWallet(WalletProtobufSerializer.parseToProto(stream), wallet); time = wallet.getEarliestKeyCreationTime(); } @@ -102,23 +104,24 @@ public class BitSquareWalletAppKit extends WalletAppKit // Make sure we shut down cleanly. installShutdownHook(); // TODO: Be able to use the provided download listener when doing a blocking startup. - final DownloadListener listener = new DownloadListener(); + @NotNull final DownloadListener listener = new DownloadListener(); vPeerGroup.startBlockChainDownload(listener); listener.await(); } else { + //TODO Futures.addCallback(vPeerGroup.start(), new FutureCallback() { @Override public void onSuccess(State result) { - final PeerEventListener l = downloadListener == null ? new DownloadListener() : downloadListener; + @NotNull final PeerEventListener l = downloadListener == null ? new DownloadListener() : downloadListener; vPeerGroup.startBlockChainDownload(l); } @Override - public void onFailure(Throwable t) + public void onFailure(@NotNull Throwable t) { throw new RuntimeException(t); } diff --git a/src/main/java/io/bitsquare/btc/BlockChainFacade.java b/src/main/java/io/bitsquare/btc/BlockChainFacade.java index f92d5670a3..6d2a254dbe 100644 --- a/src/main/java/io/bitsquare/btc/BlockChainFacade.java +++ b/src/main/java/io/bitsquare/btc/BlockChainFacade.java @@ -2,10 +2,12 @@ package io.bitsquare.btc; import com.google.inject.Inject; import io.bitsquare.bank.BankAccount; +import org.jetbrains.annotations.Nullable; /** * That facade delivers blockchain functionality from the bitcoinJ library */ +@SuppressWarnings({"SameReturnValue", "UnusedParameters"}) public class BlockChainFacade { @Inject @@ -41,6 +43,7 @@ public class BlockChainFacade return true; } + @Nullable private byte[] getDataForTxWithAddress(String address) { // TODO diff --git a/src/main/java/io/bitsquare/btc/BtcFormatter.java b/src/main/java/io/bitsquare/btc/BtcFormatter.java index c126f0f72b..c01a795b0e 100644 --- a/src/main/java/io/bitsquare/btc/BtcFormatter.java +++ b/src/main/java/io/bitsquare/btc/BtcFormatter.java @@ -2,18 +2,19 @@ package io.bitsquare.btc; import com.google.bitcoin.core.Utils; import io.bitsquare.gui.util.BitSquareConverter; -import io.bitsquare.gui.util.BitSquareFormatter; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.Locale; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // TODO public class BtcFormatter { - public static final BigInteger BTC = new BigInteger("100000000"); + private static final BigInteger BTC = new BigInteger("100000000"); private static final Logger log = LoggerFactory.getLogger(BtcFormatter.class); + @NotNull public static BigInteger mBTC = new BigInteger("100000"); @@ -23,7 +24,7 @@ public class BtcFormatter } //TODO - public static double satoshiToBTC(BigInteger satoshis) + public static double satoshiToBTC(@NotNull BigInteger satoshis) { return satoshis.doubleValue() / BTC.doubleValue(); } @@ -38,7 +39,7 @@ public class BtcFormatter try { // only "." as decimal sep supported by Utils.toNanoCoins - DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH); + @NotNull DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH); decimalFormat.setMaximumFractionDigits(10); decimalFormat.setMinimumFractionDigits(10); String stringValue = decimalFormat.format(value); @@ -49,12 +50,4 @@ public class BtcFormatter return BigInteger.ZERO; } } - - public static String formatSatoshis(BigInteger satoshis, boolean useBTC) - { - if (useBTC) - return BitSquareFormatter.formatDouble(satoshiToBTC(satoshis), 8) + " BTC"; - else - return BitSquareFormatter.formatDouble(satoshiToBTC(satoshis), 8); - } } diff --git a/src/main/java/io/bitsquare/btc/BtcValidator.java b/src/main/java/io/bitsquare/btc/BtcValidator.java index a37bd3a312..0a1a397357 100644 --- a/src/main/java/io/bitsquare/btc/BtcValidator.java +++ b/src/main/java/io/bitsquare/btc/BtcValidator.java @@ -6,6 +6,7 @@ import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.Transaction; import com.google.inject.Inject; import java.math.BigInteger; +import org.jetbrains.annotations.Nullable; public class BtcValidator { @@ -17,7 +18,7 @@ public class BtcValidator BtcValidator.params = params; } - public static boolean isMinSpendableAmount(BigInteger amount) + public static boolean isMinSpendableAmount(@Nullable BigInteger amount) { return amount != null && amount.compareTo(FeePolicy.TX_FEE.add(Transaction.MIN_NONDUST_OUTPUT)) > 0; } diff --git a/src/main/java/io/bitsquare/btc/FeePolicy.java b/src/main/java/io/bitsquare/btc/FeePolicy.java index 344164db41..c6f8abab16 100644 --- a/src/main/java/io/bitsquare/btc/FeePolicy.java +++ b/src/main/java/io/bitsquare/btc/FeePolicy.java @@ -3,6 +3,7 @@ package io.bitsquare.btc; import com.google.bitcoin.core.*; import com.google.inject.Inject; import java.math.BigInteger; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,6 +27,7 @@ public class FeePolicy } //TODO other users or dev address? use donation option list? (dev, other users, wikileaks, tor, sub projects (bitcoinj, tomp2p,...)...) + @Nullable public Address getAddressForRegistrationFee() { try @@ -39,6 +41,7 @@ public class FeePolicy } //TODO get address form arbitrator list + @Nullable public Address getAddressForCreateOfferFee() { try @@ -52,6 +55,7 @@ public class FeePolicy } //TODO get address form the intersection of both traders arbitrator lists + @Nullable public Address getAddressForTakeOfferFee() { try diff --git a/src/main/java/io/bitsquare/btc/WalletFacade.java b/src/main/java/io/bitsquare/btc/WalletFacade.java index 929095df96..18acfc9fd3 100644 --- a/src/main/java/io/bitsquare/btc/WalletFacade.java +++ b/src/main/java/io/bitsquare/btc/WalletFacade.java @@ -19,6 +19,7 @@ import io.bitsquare.btc.listeners.BalanceListener; import io.bitsquare.btc.listeners.ConfidenceListener; import io.bitsquare.crypto.CryptoFacade; import io.bitsquare.storage.Storage; +import java.io.Serializable; import java.math.BigInteger; import java.util.*; import java.util.concurrent.locks.ReentrantLock; @@ -26,6 +27,8 @@ import java.util.stream.Collectors; import javafx.application.Platform; import javafx.util.Pair; import javax.annotation.concurrent.GuardedBy; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,6 +49,7 @@ public class WalletFacade private final ReentrantLock lock = Threading.lock("lock"); + @NotNull private final String saveAddressEntryListId; private final NetworkParameters params; private final BitSquareWalletAppKit walletAppKit; @@ -57,6 +61,7 @@ public class WalletFacade private final List balanceListeners = new ArrayList<>(); private BitSquareWallet wallet; private WalletEventListener walletEventListener; + @NotNull @GuardedBy("lock") private List addressEntryList = new ArrayList<>(); @@ -131,11 +136,11 @@ public class WalletFacade @Override public void onCoinsReceived(Wallet wallet, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { - notifyBalanceListeners(tx); + notifyBalanceListeners(); } @Override - public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) + public void onTransactionConfidenceChanged(Wallet wallet, @NotNull Transaction tx) { notifyConfidenceListeners(tx); } @@ -143,7 +148,7 @@ public class WalletFacade @Override public void onCoinsSent(Wallet wallet, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { - notifyBalanceListeners(tx); + notifyBalanceListeners(); } @Override @@ -168,30 +173,20 @@ public class WalletFacade }; wallet.addEventListener(walletEventListener); - Object object = storage.read(saveAddressEntryListId); - if (object instanceof List) + Serializable serializable = storage.read(saveAddressEntryListId); + List savedAddressEntryList = (List) serializable; + if (serializable instanceof List) { - List savedAddressEntryList = (List) object; - if (savedAddressEntryList != null) - { - addressEntryList = savedAddressEntryList; - } - else - { - lock.lock(); - try - { - ECKey registrationKey = wallet.getKeys().get(0); - AddressEntry registrationAddressEntry = new AddressEntry(registrationKey, params, AddressEntry.AddressContext.REGISTRATION_FEE); - addressEntryList.add(registrationAddressEntry); - } finally - { - lock.unlock(); - } - - saveAddressInfoList(); - getNewTradeAddressEntry(); - } + addressEntryList = savedAddressEntryList; + } + else + { + lock.lock(); + ECKey registrationKey = wallet.getKeys().get(0); + addressEntryList.add(new AddressEntry(registrationKey, params, AddressEntry.AddressContext.REGISTRATION_FEE)); + lock.unlock(); + saveAddressInfoList(); + getNewTradeAddressEntry(); } } @@ -214,6 +209,7 @@ public class WalletFacade // Listener /////////////////////////////////////////////////////////////////////////////////////////// + @SuppressWarnings("UnusedReturnValue") public DownloadListener addDownloadListener(DownloadListener listener) { downloadListeners.add(listener); @@ -257,49 +253,55 @@ public class WalletFacade return ImmutableList.copyOf(addressEntryList); } + @Nullable public AddressEntry getRegistrationAddressInfo() { return getAddressInfoByAddressContext(AddressEntry.AddressContext.REGISTRATION_FEE); } + @NotNull public AddressEntry getArbitratorDepositAddressInfo() { - AddressEntry arbitratorDepositAddressEntry = getAddressInfoByAddressContext(AddressEntry.AddressContext.ARBITRATOR_DEPOSIT); + @Nullable AddressEntry arbitratorDepositAddressEntry = getAddressInfoByAddressContext(AddressEntry.AddressContext.ARBITRATOR_DEPOSIT); if (arbitratorDepositAddressEntry == null) arbitratorDepositAddressEntry = getNewArbitratorDepositAddressEntry(); return arbitratorDepositAddressEntry; } - public AddressEntry getUnusedTradeAddressInfo() + @Nullable + AddressEntry getUnusedTradeAddressInfo() { List filteredList = Lists.newArrayList(Collections2.filter(ImmutableList.copyOf(addressEntryList), addressInfo -> (addressInfo != null && addressInfo.getAddressContext().equals(AddressEntry.AddressContext.TRADE) && addressInfo.getTradeId() == null))); - if (filteredList != null && filteredList.size() > 0) + if (filteredList != null && !filteredList.isEmpty()) return filteredList.get(0); else return getNewTradeAddressEntry(); } - private AddressEntry getAddressInfoByAddressContext(AddressEntry.AddressContext addressContext) + @Nullable + private AddressEntry getAddressInfoByAddressContext(@NotNull AddressEntry.AddressContext addressContext) { - List filteredList = Lists.newArrayList(Collections2.filter(ImmutableList.copyOf(addressEntryList), addressInfo -> (addressInfo != null && addressContext != null && addressInfo.getAddressContext() != null && addressInfo.getAddressContext().equals(addressContext)))); + List filteredList = Lists.newArrayList(Collections2.filter(ImmutableList.copyOf(addressEntryList), addressInfo -> (addressInfo != null && addressInfo.getAddressContext() != null && addressInfo.getAddressContext().equals(addressContext)))); - if (filteredList != null && filteredList.size() > 0) + if (filteredList != null && !filteredList.isEmpty()) return filteredList.get(0); else return null; } + @Nullable public AddressEntry getAddressInfoByTradeID(String tradeId) { - for (AddressEntry addressEntry : ImmutableList.copyOf(addressEntryList)) + for (@NotNull AddressEntry addressEntry : ImmutableList.copyOf(addressEntryList)) { if (addressEntry.getTradeId() != null && addressEntry.getTradeId().equals(tradeId)) return addressEntry; } - AddressEntry addressEntry = getUnusedTradeAddressInfo(); + @Nullable AddressEntry addressEntry = getUnusedTradeAddressInfo(); + assert addressEntry != null; addressEntry.setTradeId(tradeId); return addressEntry; } @@ -309,41 +311,38 @@ public class WalletFacade // Create new AddressInfo objects /////////////////////////////////////////////////////////////////////////////////////////// + @NotNull public AddressEntry getNewTradeAddressEntry() { return getNewAddressEntry(AddressEntry.AddressContext.TRADE); } + @NotNull private AddressEntry getNewAddressEntry(AddressEntry.AddressContext addressContext) { - AddressEntry addressEntry = null; lock.lock(); wallet.getLock().lock(); - try - { - ECKey key = new ECKey(); - wallet.addKey(key); - wallet.addWatchedAddress(key.toAddress(params)); - addressEntry = new AddressEntry(key, params, addressContext); - addressEntryList.add(addressEntry); - saveAddressInfoList(); - } finally - { - lock.unlock(); - wallet.getLock().unlock(); - } - + @NotNull ECKey key = new ECKey(); + wallet.addKey(key); + wallet.addWatchedAddress(key.toAddress(params)); + AddressEntry addressEntry = new AddressEntry(key, params, addressContext); + addressEntryList.add(addressEntry); + saveAddressInfoList(); + lock.unlock(); + wallet.getLock().unlock(); return addressEntry; } + @NotNull private AddressEntry getNewArbitratorDepositAddressEntry() { return getNewAddressEntry(AddressEntry.AddressContext.ARBITRATOR_DEPOSIT); } + @Nullable private AddressEntry getAddressEntryByAddressString(String address) { - for (AddressEntry addressEntry : addressEntryList) + for (@NotNull AddressEntry addressEntry : addressEntryList) { if (addressEntry.getAddressString().equals(address)) return addressEntry; @@ -355,9 +354,10 @@ public class WalletFacade // TransactionConfidence /////////////////////////////////////////////////////////////////////////////////////////// - public TransactionConfidence getConfidenceForAddress(Address address) + @Nullable + public TransactionConfidence getConfidenceForAddress(@NotNull Address address) { - List transactionConfidenceList = new ArrayList<>(); + @NotNull List transactionConfidenceList = new ArrayList<>(); Set transactions = wallet.getTransactions(true); if (transactions != null) { @@ -372,22 +372,23 @@ public class WalletFacade return getMostRecentConfidence(transactionConfidenceList); } - private void notifyConfidenceListeners(Transaction tx) + private void notifyConfidenceListeners(@NotNull Transaction tx) { - for (ConfidenceListener confidenceListener : confidenceListeners) + for (@NotNull ConfidenceListener confidenceListener : confidenceListeners) { - List transactionConfidenceList = new ArrayList<>(); + @NotNull List transactionConfidenceList = new ArrayList<>(); transactionConfidenceList.add(getTransactionConfidence(tx, confidenceListener.getAddress())); - TransactionConfidence transactionConfidence = getMostRecentConfidence(transactionConfidenceList); + @Nullable TransactionConfidence transactionConfidence = getMostRecentConfidence(transactionConfidenceList); confidenceListener.onTransactionConfidenceChanged(transactionConfidence); } } - private TransactionConfidence getTransactionConfidence(Transaction tx, Address address) + @Nullable + private TransactionConfidence getTransactionConfidence(@NotNull Transaction tx, @NotNull Address address) { - List mergedOutputs = getOutputsWithConnectedOutputs(tx); - List transactionConfidenceList = new ArrayList<>(); + @NotNull List mergedOutputs = getOutputsWithConnectedOutputs(tx); + @NotNull List transactionConfidenceList = new ArrayList<>(); mergedOutputs.stream().filter(transactionOutput -> transactionOutput.getScriptPubKey().isSentToAddress() || transactionOutput.getScriptPubKey().isSentToP2SH()).forEach(transactionOutput -> { Address outputAddress = transactionOutput.getScriptPubKey().getToAddress(params); @@ -413,30 +414,32 @@ public class WalletFacade return getMostRecentConfidence(transactionConfidenceList); } - private List getOutputsWithConnectedOutputs(Transaction tx) + @NotNull + private List getOutputsWithConnectedOutputs(@NotNull Transaction tx) { List transactionOutputs = tx.getOutputs(); - List connectedOutputs = new ArrayList<>(); + @NotNull List connectedOutputs = new ArrayList<>(); // add all connected outputs from any inputs as well List transactionInputs = tx.getInputs(); - for (TransactionInput transactionInput : transactionInputs) + for (@NotNull TransactionInput transactionInput : transactionInputs) { - TransactionOutput transactionOutput = transactionInput.getConnectedOutput(); + @Nullable TransactionOutput transactionOutput = transactionInput.getConnectedOutput(); if (transactionOutput != null) connectedOutputs.add(transactionOutput); } - List mergedOutputs = new ArrayList<>(); + @NotNull List mergedOutputs = new ArrayList<>(); mergedOutputs.addAll(transactionOutputs); mergedOutputs.addAll(connectedOutputs); return mergedOutputs; } - private TransactionConfidence getMostRecentConfidence(List transactionConfidenceList) + @Nullable + private TransactionConfidence getMostRecentConfidence(@NotNull List transactionConfidenceList) { - TransactionConfidence transactionConfidence = null; - for (TransactionConfidence confidence : transactionConfidenceList) + @Nullable TransactionConfidence transactionConfidence = null; + for (@Nullable TransactionConfidence confidence : transactionConfidenceList) { if (confidence != null) { @@ -457,7 +460,9 @@ public class WalletFacade public boolean isRegistrationFeeConfirmed() { - TransactionConfidence transactionConfidence = getConfidenceForAddress(getRegistrationAddressInfo().getAddress()); + @Nullable TransactionConfidence transactionConfidence = null; + if (getRegistrationAddressInfo() != null) + transactionConfidence = getConfidenceForAddress(getRegistrationAddressInfo().getAddress()); return transactionConfidence != null && transactionConfidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.BUILDING); } @@ -471,10 +476,10 @@ public class WalletFacade return getBalance(wallet.calculateAllSpendCandidates(true), address); } - private BigInteger getBalance(LinkedList transactionOutputs, Address address) + private BigInteger getBalance(@NotNull LinkedList transactionOutputs, Address address) { BigInteger balance = BigInteger.ZERO; - for (TransactionOutput transactionOutput : transactionOutputs) + for (@NotNull TransactionOutput transactionOutput : transactionOutputs) { if (transactionOutput.getScriptPubKey().isSentToAddress() || transactionOutput.getScriptPubKey().isSentToP2SH()) { @@ -488,9 +493,9 @@ public class WalletFacade return balance; } - private void notifyBalanceListeners(Transaction tx) + private void notifyBalanceListeners() { - for (BalanceListener balanceListener : balanceListeners) + for (@NotNull BalanceListener balanceListener : balanceListeners) { BigInteger balance; if (balanceListener.getAddress() != null) @@ -507,7 +512,7 @@ public class WalletFacade return wallet.getBalance(Wallet.BalanceType.ESTIMATED); } - public BigInteger getRegistrationBalance() + BigInteger getRegistrationBalance() { return getBalanceForAddress(getRegistrationAddressInfo().getAddress()); } @@ -529,14 +534,14 @@ public class WalletFacade public boolean isUnusedTradeAddressBalanceAboveCreationFee() { - AddressEntry unUsedAddressEntry = getUnusedTradeAddressInfo(); + @Nullable AddressEntry unUsedAddressEntry = getUnusedTradeAddressInfo(); BigInteger unUsedAddressInfoBalance = getBalanceForAddress(unUsedAddressEntry.getAddress()); return unUsedAddressInfoBalance.compareTo(FeePolicy.CREATE_OFFER_FEE) > 0; } public boolean isUnusedTradeAddressBalanceAboveTakeOfferFee() { - AddressEntry unUsedAddressEntry = getUnusedTradeAddressInfo(); + @Nullable AddressEntry unUsedAddressEntry = getUnusedTradeAddressInfo(); BigInteger unUsedAddressInfoBalance = getBalanceForAddress(unUsedAddressEntry.getAddress()); return unUsedAddressInfoBalance.compareTo(FeePolicy.TAKE_OFFER_FEE) > 0; } @@ -547,6 +552,7 @@ public class WalletFacade //TODO + @SuppressWarnings({"SameReturnValue", "UnusedParameters"}) public int getNumOfPeersSeenTx(String txID) { // TODO check from blockchain @@ -559,12 +565,12 @@ public class WalletFacade // Transactions /////////////////////////////////////////////////////////////////////////////////////////// - public void payRegistrationFee(String stringifiedBankAccounts, FutureCallback callback) throws InsufficientMoneyException + public void payRegistrationFee(String stringifiedBankAccounts, @NotNull FutureCallback callback) throws InsufficientMoneyException { log.debug("payRegistrationFee"); log.trace("stringifiedBankAccounts " + stringifiedBankAccounts); - Transaction tx = new Transaction(params); + @NotNull Transaction tx = new Transaction(params); byte[] data = cryptoFacade.getEmbeddedAccountRegistrationData(getRegistrationAddressInfo().getKey(), stringifiedBankAccounts); tx.addOutput(Transaction.MIN_NONDUST_OUTPUT, new ScriptBuilder().op(OP_RETURN).data(data).build()); @@ -580,13 +586,14 @@ public class WalletFacade Wallet.SendResult sendResult = wallet.sendCoins(sendRequest); Futures.addCallback(sendResult.broadcastComplete, callback); - log.debug("Registration transaction: " + tx.toString()); + log.debug("Registration transaction: " + tx); printInputs("payRegistrationFee", tx); } - public String payCreateOfferFee(String offerId, FutureCallback callback) throws InsufficientMoneyException + @SuppressWarnings("UnusedReturnValue") + public String payCreateOfferFee(String offerId, @NotNull FutureCallback callback) throws InsufficientMoneyException { - Transaction tx = new Transaction(params); + @NotNull Transaction tx = new Transaction(params); BigInteger fee = FeePolicy.CREATE_OFFER_FEE.subtract(FeePolicy.TX_FEE); log.trace("fee: " + BtcFormatter.satoshiToString(fee)); tx.addOutput(fee, feePolicy.getAddressForCreateOfferFee()); @@ -599,14 +606,15 @@ public class WalletFacade Futures.addCallback(sendResult.broadcastComplete, callback); printInputs("payTakeOfferFee", tx); - log.debug("tx=" + tx.toString()); + log.debug("tx=" + tx); return tx.getHashAsString(); } - public String payTakeOfferFee(String offerId, FutureCallback callback) throws InsufficientMoneyException + @SuppressWarnings("UnusedReturnValue") + public String payTakeOfferFee(String offerId, @NotNull FutureCallback callback) throws InsufficientMoneyException { - Transaction tx = new Transaction(params); + @NotNull Transaction tx = new Transaction(params); BigInteger fee = FeePolicy.TAKE_OFFER_FEE.subtract(FeePolicy.TX_FEE); log.trace("fee: " + BtcFormatter.satoshiToString(fee)); tx.addOutput(fee, feePolicy.getAddressForTakeOfferFee()); @@ -619,7 +627,7 @@ public class WalletFacade Futures.addCallback(sendResult.broadcastComplete, callback); printInputs("payTakeOfferFee", tx); - log.debug("tx=" + tx.toString()); + log.debug("tx=" + tx); return tx.getHashAsString(); } @@ -629,13 +637,14 @@ public class WalletFacade // Withdrawal /////////////////////////////////////////////////////////////////////////////////////////// + @SuppressWarnings("UnusedReturnValue") public String sendFunds(String withdrawFromAddress, String withdrawToAddress, String changeAddress, - BigInteger amount, - FutureCallback callback) throws AddressFormatException, InsufficientMoneyException, IllegalArgumentException + @NotNull BigInteger amount, + @NotNull FutureCallback callback) throws AddressFormatException, InsufficientMoneyException, IllegalArgumentException { - Transaction tx = new Transaction(params); + @NotNull Transaction tx = new Transaction(params); tx.addOutput(amount.subtract(FeePolicy.TX_FEE), new Address(params, withdrawToAddress)); Wallet.SendRequest sendRequest = Wallet.SendRequest.forTx(tx); @@ -648,7 +657,7 @@ public class WalletFacade Futures.addCallback(sendResult.broadcastComplete, callback); printInputs("sendFunds", tx); - log.debug("tx=" + tx.toString()); + log.debug("tx=" + tx); return tx.getHashAsString(); } @@ -660,6 +669,7 @@ public class WalletFacade // 1. step: deposit tx // Offerer creates the 2of3 multiSig deposit tx with his unsigned input and change output + @NotNull public Transaction offererCreatesMSTxAndAddPayment(BigInteger offererInputAmount, String offererPubKey, String takerPubKey, String arbitratorPubKey, String tradeId) throws InsufficientMoneyException { log.debug("offererCreatesMSTxAndAddPayment"); @@ -675,12 +685,12 @@ public class WalletFacade // We don't commit that tx to the wallet as it will be changed later and it's not signed yet. // So it will not change the wallet balance. // The btc tx fee will be included by the completeTx() call, so we don't need to add it manually. - Transaction tx = new Transaction(params); + @NotNull Transaction tx = new Transaction(params); Script multiSigOutputScript = getMultiSigScript(offererPubKey, takerPubKey, arbitratorPubKey); tx.addOutput(offererInputAmount, multiSigOutputScript); Wallet.SendRequest sendRequest = Wallet.SendRequest.forTx(tx); - AddressEntry addressEntry = getAddressInfoByTradeID(tradeId); + @Nullable AddressEntry addressEntry = getAddressInfoByTradeID(tradeId); addressEntry.setTradeId(tradeId); // we allow spending of unconfirmed tx (double spend risk is low and usability would suffer if we need to wait for 1 confirmation) sendRequest.coinSelector = new AddressBasedCoinSelector(params, addressEntry, true); @@ -704,12 +714,13 @@ public class WalletFacade log.trace("Check if wallet is consistent: result=" + wallet.isConsistent()); printInputs("offererCreatesMSTxAndAddPayment", tx); - log.debug("tx = " + tx.toString()); + log.debug("tx = " + tx); return tx; } // 2. step: deposit tx // Taker adds his input and change output, changes the multiSig amount to the correct value and sign his input + @NotNull public Transaction takerAddPaymentAndSignTx(BigInteger takerInputAmount, BigInteger msOutputAmount, String offererPubKey, @@ -734,12 +745,12 @@ public class WalletFacade // Both traders pay 1 times a fee, so it is equally split between them // We do exactly the same as in the 1. step but with the takers input. - Transaction tempTx = new Transaction(params); + @NotNull Transaction tempTx = new Transaction(params); Script multiSigOutputScript = getMultiSigScript(offererPubKey, takerPubKey, arbitratorPubKey); tempTx.addOutput(takerInputAmount, multiSigOutputScript); Wallet.SendRequest sendRequest = Wallet.SendRequest.forTx(tempTx); - AddressEntry addressEntry = getAddressInfoByTradeID(tradeId); + @Nullable AddressEntry addressEntry = getAddressInfoByTradeID(tradeId); addressEntry.setTradeId(tradeId); // we allow spending of unconfirmed tx (double spend risk is low and usability would suffer if we need to wait for 1 confirmation) sendRequest.coinSelector = new AddressBasedCoinSelector(params, addressEntry, true); @@ -760,7 +771,7 @@ public class WalletFacade // Now we construct the real 2of3 multiSig tx from the serialized offerers tx - Transaction tx = new Transaction(params, Utils.parseAsHexOrBase58(offerersPartialDepositTxAsHex)); + @NotNull Transaction tx = new Transaction(params, Utils.parseAsHexOrBase58(offerersPartialDepositTxAsHex)); log.trace("offerersPartialDepositTx=" + tx); // The serialized offerers tx looks like: @@ -786,10 +797,10 @@ public class WalletFacade log.error("input or input.getConnectedOutput() is null: " + input); Script scriptPubKey = input.getConnectedOutput().getScriptPubKey(); - ECKey sigKey = input.getOutpoint().getConnectedKey(wallet); + @Nullable ECKey sigKey = input.getOutpoint().getConnectedKey(wallet); Sha256Hash hash = tx.hashForSignature(1, scriptPubKey, Transaction.SigHash.ALL, false); ECKey.ECDSASignature ecSig = sigKey.sign(hash); - TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false); + @NotNull TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false); if (scriptPubKey.isSentToRawPubKey()) input.setScriptSig(ScriptBuilder.createInputScript(txSig)); else if (scriptPubKey.isSentToAddress()) @@ -818,20 +829,21 @@ public class WalletFacade log.trace("Check if wallet is consistent before commit: result=" + wallet.isConsistent()); printInputs("takerAddPaymentAndSignTx", tx); - log.debug("tx = " + tx.toString()); + log.debug("tx = " + tx); return tx; } // 3. step: deposit tx // Offerer signs tx and publishes it + @NotNull public Transaction offererSignAndPublishTx(String offerersFirstTxAsHex, String takersSignedTxAsHex, String takersSignedConnOutAsHex, String takersSignedScriptSigAsHex, long offererTxOutIndex, long takerTxOutIndex, - FutureCallback callback) + @NotNull FutureCallback callback) { log.debug("offererSignAndPublishTx"); log.trace("inputs: "); @@ -839,35 +851,35 @@ public class WalletFacade log.trace("takersSignedTxAsHex=" + takersSignedTxAsHex); log.trace("takersSignedConnOutAsHex=" + takersSignedConnOutAsHex); log.trace("takersSignedScriptSigAsHex=" + takersSignedScriptSigAsHex); - log.trace("callback=" + callback.toString()); + log.trace("callback=" + callback); // We create an empty tx (did not find a way to manipulate a tx input, otherwise the takers tx could be used directly and add the offerers input and output) - Transaction tx = new Transaction(params); + @NotNull Transaction tx = new Transaction(params); // offerers first tx - Transaction offerersFirstTx = new Transaction(params, Utils.parseAsHexOrBase58(offerersFirstTxAsHex)); + @NotNull Transaction offerersFirstTx = new Transaction(params, Utils.parseAsHexOrBase58(offerersFirstTxAsHex)); printInputs("offerersFirstTx", offerersFirstTx); - log.trace("offerersFirstTx = " + offerersFirstTx.toString()); + log.trace("offerersFirstTx = " + offerersFirstTx); // add input - Transaction offerersFirstTxConnOut = wallet.getTransaction(offerersFirstTx.getInput(0).getOutpoint().getHash()); // pass that around! - TransactionOutPoint offerersFirstTxOutPoint = new TransactionOutPoint(params, offererTxOutIndex, offerersFirstTxConnOut); + @Nullable Transaction offerersFirstTxConnOut = wallet.getTransaction(offerersFirstTx.getInput(0).getOutpoint().getHash()); // pass that around! + @NotNull TransactionOutPoint offerersFirstTxOutPoint = new TransactionOutPoint(params, offererTxOutIndex, offerersFirstTxConnOut); //TransactionInput offerersFirstTxInput = new TransactionInput(params, tx, offerersFirstTx.getInput(0).getScriptBytes(), offerersFirstTxOutPoint); // pass that around! getScriptBytes = empty bytes array - TransactionInput offerersFirstTxInput = new TransactionInput(params, tx, new byte[]{}, offerersFirstTxOutPoint); // pass that around! getScriptBytes = empty bytes array + @NotNull TransactionInput offerersFirstTxInput = new TransactionInput(params, tx, new byte[]{}, offerersFirstTxOutPoint); // pass that around! getScriptBytes = empty bytes array offerersFirstTxInput.setParent(tx); tx.addInput(offerersFirstTxInput); // takers signed tx - Transaction takersSignedTx = new Transaction(params, Utils.parseAsHexOrBase58(takersSignedTxAsHex)); + @NotNull Transaction takersSignedTx = new Transaction(params, Utils.parseAsHexOrBase58(takersSignedTxAsHex)); printInputs("takersSignedTxInput", takersSignedTx); - log.trace("takersSignedTx = " + takersSignedTx.toString()); + log.trace("takersSignedTx = " + takersSignedTx); // add input - Transaction takersSignedTxConnOut = new Transaction(params, Utils.parseAsHexOrBase58(takersSignedConnOutAsHex)); - TransactionOutPoint takersSignedTxOutPoint = new TransactionOutPoint(params, takerTxOutIndex, takersSignedTxConnOut); - TransactionInput takersSignedTxInput = new TransactionInput(params, tx, Utils.parseAsHexOrBase58(takersSignedScriptSigAsHex), takersSignedTxOutPoint); + @NotNull Transaction takersSignedTxConnOut = new Transaction(params, Utils.parseAsHexOrBase58(takersSignedConnOutAsHex)); + @NotNull TransactionOutPoint takersSignedTxOutPoint = new TransactionOutPoint(params, takerTxOutIndex, takersSignedTxConnOut); + @NotNull TransactionInput takersSignedTxInput = new TransactionInput(params, tx, Utils.parseAsHexOrBase58(takersSignedScriptSigAsHex), takersSignedTxOutPoint); takersSignedTxInput.setParent(tx); tx.addInput(takersSignedTxInput); @@ -880,7 +892,7 @@ public class WalletFacade tx.addOutput(takersSignedTx.getOutput(2)); printInputs("tx", tx); - log.trace("tx = " + tx.toString()); + log.trace("tx = " + tx); log.trace("Wallet balance before signing: " + wallet.getBalance()); // sign the input @@ -889,10 +901,10 @@ public class WalletFacade log.error("input or input.getConnectedOutput() is null: " + input); Script scriptPubKey = input.getConnectedOutput().getScriptPubKey(); - ECKey sigKey = input.getOutpoint().getConnectedKey(wallet); + @Nullable ECKey sigKey = input.getOutpoint().getConnectedKey(wallet); Sha256Hash hash = tx.hashForSignature(0, scriptPubKey, Transaction.SigHash.ALL, false); ECKey.ECDSASignature ecSig = sigKey.sign(hash); - TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false); + @NotNull TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false); if (scriptPubKey.isSentToRawPubKey()) input.setScriptSig(ScriptBuilder.createInputScript(txSig)); else if (scriptPubKey.isSentToAddress()) @@ -921,7 +933,7 @@ public class WalletFacade tx.verify(); printInputs("tx", tx); - log.debug("tx = " + tx.toString()); + log.debug("tx = " + tx); log.trace("Wallet balance before broadcastTransaction: " + wallet.getBalance()); log.trace("Check if wallet is consistent before broadcastTransaction: result=" + wallet.isConsistent()); @@ -931,7 +943,7 @@ public class WalletFacade Futures.addCallback(broadcastComplete, callback); printInputs("tx", tx); - log.debug("tx = " + tx.toString()); + log.debug("tx = " + tx); return tx; } @@ -941,7 +953,7 @@ public class WalletFacade log.trace("takerCommitDepositTx"); log.trace("inputs: "); log.trace("depositTxID=" + depositTxAsHex); - Transaction depositTx = new Transaction(params, Utils.parseAsHexOrBase58(depositTxAsHex)); + @NotNull Transaction depositTx = new Transaction(params, Utils.parseAsHexOrBase58(depositTxAsHex)); log.trace("depositTx=" + depositTx); // boolean isAlreadyInWallet = wallet.maybeCommitTx(depositTx); //log.trace("isAlreadyInWallet=" + isAlreadyInWallet); @@ -961,6 +973,7 @@ public class WalletFacade } // 5. step payout tx: Offerer creates payout tx and signs it + @NotNull public Pair offererCreatesAndSignsPayoutTx(String depositTxID, BigInteger offererPaybackAmount, BigInteger takerPaybackAmount, @@ -975,27 +988,29 @@ public class WalletFacade log.trace("takerAddress=" + takerAddress); // Offerer has published depositTx earlier, so he has it in his wallet - Transaction depositTx = wallet.getTransaction(new Sha256Hash(depositTxID)); + @Nullable Transaction depositTx = wallet.getTransaction(new Sha256Hash(depositTxID)); String depositTxAsHex = Utils.bytesToHexString(depositTx.bitcoinSerialize()); // We create the payout tx - Transaction tx = createPayoutTx(depositTxAsHex, offererPaybackAmount, takerPaybackAmount, getAddressInfoByTradeID(tradeID).getAddressString(), takerAddress); + @NotNull Transaction tx = createPayoutTx(depositTxAsHex, offererPaybackAmount, takerPaybackAmount, getAddressInfoByTradeID(tradeID).getAddressString(), takerAddress); // We create the signature for that tx - TransactionOutput multiSigOutput = tx.getInput(0).getConnectedOutput(); + @Nullable TransactionOutput multiSigOutput = tx.getInput(0).getConnectedOutput(); Script multiSigScript = multiSigOutput.getScriptPubKey(); Sha256Hash sigHash = tx.hashForSignature(0, multiSigScript, Transaction.SigHash.ALL, false); ECKey.ECDSASignature offererSignature = getAddressInfoByTradeID(tradeID).getKey().sign(sigHash); - TransactionSignature offererTxSig = new TransactionSignature(offererSignature, Transaction.SigHash.ALL, false); + @NotNull TransactionSignature offererTxSig = new TransactionSignature(offererSignature, Transaction.SigHash.ALL, false); Script inputScript = ScriptBuilder.createMultiSigInputScript(ImmutableList.of(offererTxSig)); tx.getInput(0).setScriptSig(inputScript); - log.trace("sigHash=" + sigHash.toString()); + log.trace("sigHash=" + sigHash); return new Pair<>(offererSignature, depositTxAsHex); } // 6. step payout tx: Taker signs and publish tx + @SuppressWarnings("UnusedReturnValue") + @NotNull public Transaction takerSignsAndSendsTx(String depositTxAsHex, String offererSignatureR, String offererSignatureS, @@ -1003,7 +1018,7 @@ public class WalletFacade BigInteger takerPaybackAmount, String offererAddress, String tradeID, - FutureCallback callback) throws AddressFormatException + @NotNull FutureCallback callback) throws AddressFormatException { log.debug("takerSignsAndSendsTx"); log.trace("inputs: "); @@ -1013,22 +1028,22 @@ public class WalletFacade log.trace("offererPaybackAmount=" + BtcFormatter.satoshiToString(offererPaybackAmount)); log.trace("takerPaybackAmount=" + BtcFormatter.satoshiToString(takerPaybackAmount)); log.trace("offererAddress=" + offererAddress); - log.trace("callback=" + callback.toString()); + log.trace("callback=" + callback); // We create the payout tx - Transaction tx = createPayoutTx(depositTxAsHex, offererPaybackAmount, takerPaybackAmount, offererAddress, getAddressInfoByTradeID(tradeID).getAddressString()); + @NotNull Transaction tx = createPayoutTx(depositTxAsHex, offererPaybackAmount, takerPaybackAmount, offererAddress, getAddressInfoByTradeID(tradeID).getAddressString()); // We sign that tx with our key and apply the signature form the offerer - TransactionOutput multiSigOutput = tx.getInput(0).getConnectedOutput(); + @Nullable TransactionOutput multiSigOutput = tx.getInput(0).getConnectedOutput(); Script multiSigScript = multiSigOutput.getScriptPubKey(); Sha256Hash sigHash = tx.hashForSignature(0, multiSigScript, Transaction.SigHash.ALL, false); - log.trace("sigHash=" + sigHash.toString()); + log.trace("sigHash=" + sigHash); ECKey.ECDSASignature takerSignature = getAddressInfoByTradeID(tradeID).getKey().sign(sigHash); - TransactionSignature takerTxSig = new TransactionSignature(takerSignature, Transaction.SigHash.ALL, false); + @NotNull TransactionSignature takerTxSig = new TransactionSignature(takerSignature, Transaction.SigHash.ALL, false); - ECKey.ECDSASignature offererSignature = new ECKey.ECDSASignature(new BigInteger(offererSignatureR), new BigInteger(offererSignatureS)); - TransactionSignature offererTxSig = new TransactionSignature(offererSignature, Transaction.SigHash.ALL, false); + @NotNull ECKey.ECDSASignature offererSignature = new ECKey.ECDSASignature(new BigInteger(offererSignatureR), new BigInteger(offererSignatureS)); + @NotNull TransactionSignature offererTxSig = new TransactionSignature(offererSignature, Transaction.SigHash.ALL, false); Script inputScript = ScriptBuilder.createMultiSigInputScript(ImmutableList.of(offererTxSig, takerTxSig)); tx.getInput(0).setScriptSig(inputScript); @@ -1048,7 +1063,7 @@ public class WalletFacade log.trace("getTransactions.size=" + wallet.getTransactions(true).size()); log.trace("Check if wallet is consistent: result=" + wallet.isConsistent()); printInputs("takerSignsAndSendsTx", tx); - log.debug("tx = " + tx.toString()); + log.debug("tx = " + tx); return tx; } @@ -1072,15 +1087,16 @@ public class WalletFacade private Script getMultiSigScript(String offererPubKey, String takerPubKey, String arbitratorPubKey) { - ECKey offererKey = new ECKey(null, Utils.parseAsHexOrBase58(offererPubKey)); - ECKey takerKey = new ECKey(null, Utils.parseAsHexOrBase58(takerPubKey)); - ECKey arbitratorKey = new ECKey(null, Utils.parseAsHexOrBase58(arbitratorPubKey)); + @NotNull ECKey offererKey = new ECKey(null, Utils.parseAsHexOrBase58(offererPubKey)); + @NotNull ECKey takerKey = new ECKey(null, Utils.parseAsHexOrBase58(takerPubKey)); + @NotNull ECKey arbitratorKey = new ECKey(null, Utils.parseAsHexOrBase58(arbitratorPubKey)); List keys = ImmutableList.of(offererKey, takerKey, arbitratorKey); return ScriptBuilder.createMultiSigOutputScript(2, keys); } + @NotNull private Transaction createPayoutTx(String depositTxAsHex, BigInteger offererPaybackAmount, BigInteger takerPaybackAmount, @@ -1095,9 +1111,9 @@ public class WalletFacade log.trace("offererAddress=" + offererAddress); log.trace("takerAddress=" + takerAddress); - Transaction depositTx = new Transaction(params, Utils.parseAsHexOrBase58(depositTxAsHex)); + @NotNull Transaction depositTx = new Transaction(params, Utils.parseAsHexOrBase58(depositTxAsHex)); TransactionOutput multiSigOutput = depositTx.getOutput(0); - Transaction tx = new Transaction(params); + @NotNull Transaction tx = new Transaction(params); tx.addInput(multiSigOutput); tx.addOutput(offererPaybackAmount, new Address(params, offererAddress)); tx.addOutput(takerPaybackAmount, new Address(params, takerAddress)); @@ -1105,9 +1121,9 @@ public class WalletFacade return tx; } - private void printInputs(String tracePrefix, Transaction tx) + private void printInputs(String tracePrefix, @NotNull Transaction tx) { - for (TransactionInput input : tx.getInputs()) + for (@NotNull TransactionInput input : tx.getInputs()) if (input.getConnectedOutput() != null) log.trace(tracePrefix + ": " + BtcFormatter.satoshiToString(input.getConnectedOutput().getValue())); else @@ -1121,7 +1137,7 @@ public class WalletFacade public static interface DownloadListener { - void progress(double percent, int blocksSoFar, Date date); + void progress(double percent); void doneDownload(); } @@ -1144,13 +1160,13 @@ public class WalletFacade private void onProgressInUserThread(double percent, int blocksSoFar, final Date date) { - for (DownloadListener downloadListener : downloadListeners) - downloadListener.progress(percent, blocksSoFar, date); + for (@NotNull DownloadListener downloadListener : downloadListeners) + downloadListener.progress(percent); } private void onDoneDownloadInUserThread() { - for (DownloadListener downloadListener : downloadListeners) + for (@NotNull DownloadListener downloadListener : downloadListeners) downloadListener.doneDownload(); } } diff --git a/src/main/java/io/bitsquare/crypto/CryptoFacade.java b/src/main/java/io/bitsquare/crypto/CryptoFacade.java index d1e6ab6bab..3f2a00b217 100644 --- a/src/main/java/io/bitsquare/crypto/CryptoFacade.java +++ b/src/main/java/io/bitsquare/crypto/CryptoFacade.java @@ -5,6 +5,7 @@ import com.google.bitcoin.core.Utils; import com.google.common.base.Charsets; import com.google.inject.Inject; import java.security.SignatureException; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,13 +23,13 @@ public class CryptoFacade } - public byte[] getEmbeddedAccountRegistrationData(ECKey registrationKey, String stringifiedBankAccounts) + public byte[] getEmbeddedAccountRegistrationData(@NotNull ECKey registrationKey, String stringifiedBankAccounts) { String signedBankAccountIDs = registrationKey.signMessage(stringifiedBankAccounts); return Utils.sha256hash160(concatenateChunks(stringifiedBankAccounts, signedBankAccountIDs).getBytes(Charsets.UTF_8)); } - public String signContract(ECKey key, String contractAsJson) + public String signContract(@NotNull ECKey key, String contractAsJson) { return key.signMessage(contractAsJson); } @@ -38,7 +39,7 @@ public class CryptoFacade { try { - ECKey key = new ECKey(null, pubKey, true); + @NotNull ECKey key = new ECKey(null, pubKey, true); key.verifyMessage(msg, sig); return true; } catch (SignatureException e) @@ -55,10 +56,11 @@ public class CryptoFacade private byte[] createHash(String msg, String sig) { - byte[] hashBytes = concatenateChunks(msg, sig).getBytes(Charsets.UTF_8); + @NotNull byte[] hashBytes = concatenateChunks(msg, sig).getBytes(Charsets.UTF_8); return Utils.sha256hash160(hashBytes); } + @NotNull private String concatenateChunks(String stringifiedBankAccounts, String signedBankAccountIDs) { return stringifiedBankAccounts + signedBankAccountIDs; diff --git a/src/main/java/io/bitsquare/di/BitSquareModule.java b/src/main/java/io/bitsquare/di/BitSquareModule.java index faee876566..65df03759a 100644 --- a/src/main/java/io/bitsquare/di/BitSquareModule.java +++ b/src/main/java/io/bitsquare/di/BitSquareModule.java @@ -22,8 +22,9 @@ import io.bitsquare.trade.Trading; import io.bitsquare.trade.orderbook.OrderBook; import io.bitsquare.trade.orderbook.OrderBookFilter; import io.bitsquare.user.User; -import io.bitsquare.util.Utilities; -import java.io.File; +import io.bitsquare.util.FileUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class BitSquareModule extends AbstractModule { @@ -66,9 +67,10 @@ class BitSquareWalletAppKitProvider implements Provider this.networkParameters = networkParameters; } + @NotNull public BitSquareWalletAppKit get() { - return new BitSquareWalletAppKit(networkParameters, new File(Utilities.getRootDir()), WalletFacade.WALLET_PREFIX); + return new BitSquareWalletAppKit(networkParameters, FileUtil.getRootDirectory()); } } @@ -82,9 +84,10 @@ class NetworkParametersProvider implements Provider this.networkType = networkType; } + @Nullable public NetworkParameters get() { - NetworkParameters result = null; + @Nullable NetworkParameters result = null; switch (networkType) { diff --git a/src/main/java/io/bitsquare/di/GuiceControllerFactory.java b/src/main/java/io/bitsquare/di/GuiceControllerFactory.java index d271e92278..dda883f700 100644 --- a/src/main/java/io/bitsquare/di/GuiceControllerFactory.java +++ b/src/main/java/io/bitsquare/di/GuiceControllerFactory.java @@ -11,7 +11,7 @@ import javafx.util.Callback; * Once set, make sure you do not use the static methods on * {@link javafx.fxml.FXMLLoader} when creating your JavaFX node. */ -public class GuiceControllerFactory implements Callback, Object> +class GuiceControllerFactory implements Callback, Object> { private final Injector injector; diff --git a/src/main/java/io/bitsquare/di/GuiceFXMLLoader.java b/src/main/java/io/bitsquare/di/GuiceFXMLLoader.java index 6a2015f379..5fad4e0829 100644 --- a/src/main/java/io/bitsquare/di/GuiceFXMLLoader.java +++ b/src/main/java/io/bitsquare/di/GuiceFXMLLoader.java @@ -4,7 +4,7 @@ import com.google.inject.Injector; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXMLLoader; -import javafx.util.BuilderFactory; +import org.jetbrains.annotations.Nullable; /** * Guice support for fxml controllers @@ -12,9 +12,11 @@ import javafx.util.BuilderFactory; public class GuiceFXMLLoader extends FXMLLoader { + @Nullable private static Injector injector = null; - public GuiceFXMLLoader() + // not used yet + /* public GuiceFXMLLoader() { super(); setupControllerFactory(); @@ -26,19 +28,20 @@ public class GuiceFXMLLoader extends FXMLLoader setupControllerFactory(); } + public GuiceFXMLLoader(URL url, ResourceBundle resourceBundle, BuilderFactory builderFactory) + { + super(url, resourceBundle, builderFactory); + setupControllerFactory(); + } */ + public GuiceFXMLLoader(URL url, ResourceBundle resourceBundle) { super(url, resourceBundle); setupControllerFactory(); } - public GuiceFXMLLoader(URL url, ResourceBundle resourceBundle, BuilderFactory builderFactory) - { - super(url, resourceBundle, builderFactory); - setupControllerFactory(); - } - public static void setInjector(Injector injector) + public static void setInjector(@Nullable Injector injector) { GuiceFXMLLoader.injector = injector; } diff --git a/src/main/java/io/bitsquare/gui/ChildController.java b/src/main/java/io/bitsquare/gui/ChildController.java index 03a20c98db..ed54af9d4a 100644 --- a/src/main/java/io/bitsquare/gui/ChildController.java +++ b/src/main/java/io/bitsquare/gui/ChildController.java @@ -1,8 +1,10 @@ package io.bitsquare.gui; +import org.jetbrains.annotations.NotNull; + public interface ChildController { - void setNavigationController(NavigationController navigationController); + void setNavigationController(@NotNull NavigationController navigationController); void cleanup(); } diff --git a/src/main/java/io/bitsquare/gui/MainController.java b/src/main/java/io/bitsquare/gui/MainController.java index bef647cc50..12f323ff27 100644 --- a/src/main/java/io/bitsquare/gui/MainController.java +++ b/src/main/java/io/bitsquare/gui/MainController.java @@ -9,6 +9,7 @@ import io.bitsquare.di.GuiceFXMLLoader; import io.bitsquare.gui.components.NetworkSyncPane; import io.bitsquare.gui.market.MarketController; import io.bitsquare.gui.util.Icons; +import io.bitsquare.gui.util.Transitions; import io.bitsquare.locale.Localisation; import io.bitsquare.msg.MessageFacade; import io.bitsquare.msg.TradeMessage; @@ -19,7 +20,6 @@ import io.bitsquare.user.User; import java.io.IOException; import java.math.BigInteger; import java.net.URL; -import java.util.Date; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.collections.FXCollections; @@ -36,6 +36,8 @@ import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.util.StringConverter; import net.tomp2p.peers.PeerAddress; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,23 +46,19 @@ public class MainController implements Initializable, NavigationController private static final Logger log = LoggerFactory.getLogger(MainController.class); private static MainController mainController; - private final User user; private final WalletFacade walletFacade; private final MessageFacade messageFacade; private final Trading trading; private final Storage storage; - private final String selectedNavigationItemStorageId; private final ToggleGroup toggleGroup = new ToggleGroup(); + @Nullable private ChildController childController; - private NavigationItem selectedNavigationItem; - private NetworkSyncPane networkSyncPane; private ToggleButton prevToggleButton; private Image prevToggleButtonIcon; private ToggleButton buyButton, sellButton, homeButton, msgButton, ordersButton, fundsButton, settingsButton; - private Pane msgButtonHolder, ordersButtonButtonHolder; - private TextField balanceTextField; + private Pane ordersButtonButtonHolder; @FXML private Pane contentPane; @@ -72,6 +70,8 @@ public class MainController implements Initializable, NavigationController private AnchorPane rootPane; @FXML private Label loadingLabel; + @FXML + private NetworkSyncPane networkSyncPane; /////////////////////////////////////////////////////////////////////////////////////////// @@ -79,7 +79,7 @@ public class MainController implements Initializable, NavigationController /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public MainController(User user, WalletFacade walletFacade, MessageFacade messageFacade, Trading trading, Storage storage) + private MainController(User user, WalletFacade walletFacade, MessageFacade messageFacade, Trading trading, Storage storage) { this.user = user; this.walletFacade = walletFacade; @@ -88,11 +88,14 @@ public class MainController implements Initializable, NavigationController this.storage = storage; MainController.mainController = this; - - selectedNavigationItemStorageId = this.getClass().getName() + ".selectedNavigationItem"; } - public static MainController getInstance() + /////////////////////////////////////////////////////////////////////////////////////////// + // Static + /////////////////////////////////////////////////////////////////////////////////////////// + + @NotNull + public static MainController INSTANCE() { return mainController; } @@ -108,81 +111,14 @@ public class MainController implements Initializable, NavigationController Platform.runLater(this::init); } - public void init() - { - networkSyncPane = new NetworkSyncPane(); - networkSyncPane.setSpacing(10); - networkSyncPane.setPrefHeight(20); - - messageFacade.init(); - - walletFacade.addDownloadListener(new WalletFacade.DownloadListener() - { - @Override - public void progress(double percent, int blocksSoFar, Date date) - { - networkSyncPane.setProgress(percent); - } - - @Override - public void doneDownload() - { - networkSyncPane.doneDownload(); - } - }); - - walletFacade.initWallet(); - - buildNavigation(); - - Object f = storage.read(selectedNavigationItemStorageId); - selectedNavigationItem = (NavigationItem) storage.read(selectedNavigationItemStorageId); - if (selectedNavigationItem == null) - selectedNavigationItem = NavigationItem.HOME; - - navigateToView(selectedNavigationItem); - - AnchorPane.setBottomAnchor(networkSyncPane, 0.0); - AnchorPane.setLeftAnchor(networkSyncPane, 0.0); - - messageFacade.addTakeOfferRequestListener(this::showTakeOfferRequest); - - loadingBar.setProgress(-1); - rootPane.getChildren().removeAll(loadingLabel, loadingBar); - - leftNavPane.setVisible(true); - rightNavPane.setVisible(true); - contentPane.setVisible(true); - } - - - private void showTakeOfferRequest(final TradeMessage tradeMessage, PeerAddress sender) - { - trading.createOffererPaymentProtocol(tradeMessage, sender); - try - { - ImageView newTradeRequestIcon = Icons.getIconImageView(Icons.MSG_ALERT); - Button alertButton = new Button("", newTradeRequestIcon); - alertButton.setId("nav-alert-button"); - alertButton.relocate(36, 19); - Tooltip.install(alertButton, new Tooltip("Someone accepted your offer")); - - alertButton.setOnAction((e) -> ordersButton.fire()); - ordersButtonButtonHolder.getChildren().add(alertButton); - - } catch (NullPointerException e) - { - log.warn("showTakeOfferRequest failed because of a NullPointerException"); - } - } - /////////////////////////////////////////////////////////////////////////////////////////// // Interface implementation: NavigationController /////////////////////////////////////////////////////////////////////////////////////////// + @Nullable @Override - public ChildController navigateToView(NavigationItem navigationItem) + public ChildController navigateToView(@NotNull NavigationItem navigationItem) { switch (navigationItem) { @@ -208,10 +144,11 @@ public class MainController implements Initializable, NavigationController buyButton.fire(); break; } - return null; + return childController; } - private ChildController loadView(NavigationItem navigationItem) + @Nullable + private ChildController loadView(@NotNull NavigationItem navigationItem) { if (childController != null) childController.cleanup(); @@ -223,18 +160,68 @@ public class MainController implements Initializable, NavigationController contentPane.getChildren().setAll(view); childController = loader.getController(); childController.setNavigationController(this); - return childController; } catch (IOException e) { e.printStackTrace(); + log.error("Loading view failed. " + navigationItem.getFxmlUrl()); } - return null; + return childController; } /////////////////////////////////////////////////////////////////////////////////////////// // Private methods /////////////////////////////////////////////////////////////////////////////////////////// + private void init() + { + messageFacade.init(); + messageFacade.addTakeOfferRequestListener(this::showTakeOfferRequest); + + walletFacade.addDownloadListener(new WalletFacade.DownloadListener() + { + @Override + public void progress(double percent) + { + networkSyncPane.setProgress(percent); + } + + @Override + public void doneDownload() + { + networkSyncPane.doneDownload(); + } + }); + + walletFacade.initWallet(); + + buildNavigation(); + + Transitions.fadeOutAndRemove(loadingLabel); + Transitions.fadeOutAndRemove(loadingBar); + + Transitions.fadeIn(leftNavPane); + Transitions.fadeIn(rightNavPane); + Transitions.fadeIn(contentPane); + + NavigationItem selectedNavigationItem = (NavigationItem) storage.read(this, "selectedNavigationItem"); + if (selectedNavigationItem == null) + selectedNavigationItem = NavigationItem.HOME; + + navigateToView(selectedNavigationItem); + } + + + private void showTakeOfferRequest(@NotNull TradeMessage tradeMessage, @NotNull PeerAddress sender) + { + trading.createOffererPaymentProtocol(tradeMessage, sender); + final Button alertButton = new Button("", Icons.getIconImageView(Icons.MSG_ALERT)); + alertButton.setId("nav-alert-button"); + alertButton.relocate(36, 19); + alertButton.setOnAction((e) -> ordersButton.fire()); + Tooltip.install(alertButton, new Tooltip("Someone accepted your offer")); + ordersButtonButtonHolder.getChildren().add(alertButton); + } + private void buildNavigation() { homeButton = addNavButton(leftNavPane, "Overview", NavigationItem.HOME); @@ -249,7 +236,7 @@ public class MainController implements Initializable, NavigationController fundsButton = addNavButton(leftNavPane, "Funds", NavigationItem.FUNDS); - msgButtonHolder = new Pane(); + final Pane msgButtonHolder = new Pane(); msgButton = addNavButton(msgButtonHolder, "Message", NavigationItem.MSG); leftNavPane.getChildren().add(msgButtonHolder); @@ -259,11 +246,12 @@ public class MainController implements Initializable, NavigationController settingsButton = addNavButton(rightNavPane, "Settings", NavigationItem.SETTINGS); } - private ToggleButton addNavButton(Pane parent, String title, NavigationItem navigationItem) + @NotNull + private ToggleButton addNavButton(@NotNull Pane parent, @NotNull String title, @NotNull NavigationItem navigationItem) { - Pane pane = new Pane(); + final Pane pane = new Pane(); pane.setPrefSize(50, 50); - ToggleButton toggleButton = new ToggleButton("", Icons.getIconImageView(navigationItem.getIcon())); + final ToggleButton toggleButton = new ToggleButton("", Icons.getIconImageView(navigationItem.getIcon())); toggleButton.setToggleGroup(toggleGroup); toggleButton.setId("nav-button"); toggleButton.setPrefSize(50, 50); @@ -280,13 +268,12 @@ public class MainController implements Initializable, NavigationController if (childController instanceof MarketController) ((MarketController) childController).setDirection(navigationItem == NavigationItem.BUY ? Direction.BUY : Direction.SELL); - storage.write(selectedNavigationItemStorageId, navigationItem); + storage.write(this, "selectedNavigationItem", navigationItem); prevToggleButton = toggleButton; - }); - Label titleLabel = new Label(title); + final Label titleLabel = new Label(title); titleLabel.setPrefWidth(60); titleLabel.setLayoutY(40); titleLabel.setId("nav-button-label"); @@ -298,34 +285,13 @@ public class MainController implements Initializable, NavigationController return toggleButton; } - private TextField addBalanceInfo(Pane parent) + private void addBalanceInfo(@NotNull Pane parent) { - balanceTextField = new TextField(); + final TextField balanceTextField = new TextField(); balanceTextField.setEditable(false); balanceTextField.setPrefWidth(90); balanceTextField.setId("nav-balance-label"); - - balanceTextField.setText(BtcFormatter.formatSatoshis(walletFacade.getWalletBalance(), false)); - - Label balanceCurrencyLabel = new Label("BTC"); - balanceCurrencyLabel.setPadding(new Insets(6, 0, 0, 0)); - HBox hBox = new HBox(); - hBox.setSpacing(2); - hBox.getChildren().setAll(balanceTextField, balanceCurrencyLabel); - - VBox vBox = new VBox(); - vBox.setPadding(new Insets(12, 0, 0, 0)); - vBox.setSpacing(2); - Label titleLabel = new Label("Balance"); - titleLabel.setMouseTransparent(true); - titleLabel.setPrefWidth(90); - titleLabel.setId("nav-button-label"); - - vBox.getChildren().setAll(hBox, titleLabel); - parent.getChildren().add(vBox); - balanceTextField.setText(BtcFormatter.satoshiToString(walletFacade.getWalletBalance())); - walletFacade.addBalanceListener(new BalanceListener() { @Override @@ -335,24 +301,43 @@ public class MainController implements Initializable, NavigationController } }); - return balanceTextField; + final Label balanceCurrencyLabel = new Label("BTC"); + balanceCurrencyLabel.setPadding(new Insets(6, 0, 0, 0)); + + final HBox hBox = new HBox(); + hBox.setSpacing(2); + hBox.getChildren().setAll(balanceTextField, balanceCurrencyLabel); + + final Label titleLabel = new Label("Balance"); + titleLabel.setMouseTransparent(true); + titleLabel.setPrefWidth(90); + titleLabel.setId("nav-button-label"); + + final VBox vBox = new VBox(); + vBox.setPadding(new Insets(12, 0, 0, 0)); + vBox.setSpacing(2); + vBox.getChildren().setAll(hBox, titleLabel); + parent.getChildren().add(vBox); } - private void addAccountComboBox(Pane parent) + private void addAccountComboBox(@NotNull Pane parent) { if (user.getBankAccounts().size() > 1) { - ComboBox accountComboBox = new ComboBox(FXCollections.observableArrayList(user.getBankAccounts())); + final ComboBox accountComboBox = new ComboBox<>(FXCollections.observableArrayList(user.getBankAccounts())); accountComboBox.setLayoutY(12); accountComboBox.setValue(user.getCurrentBankAccount()); + accountComboBox.valueProperty().addListener((ov, oldValue, newValue) -> user.setCurrentBankAccount(newValue)); accountComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(BankAccount bankAccount) + public String toString(@NotNull BankAccount bankAccount) { return bankAccount.getAccountTitle(); } + @Nullable @Override public BankAccount fromString(String s) { @@ -360,21 +345,17 @@ public class MainController implements Initializable, NavigationController } }); - VBox vBox = new VBox(); - vBox.setPadding(new Insets(12, 0, 0, 0)); - vBox.setSpacing(2); - Label titleLabel = new Label("Bank account"); + + final Label titleLabel = new Label("Bank account"); titleLabel.setMouseTransparent(true); titleLabel.setPrefWidth(90); titleLabel.setId("nav-button-label"); + final VBox vBox = new VBox(); + vBox.setPadding(new Insets(12, 0, 0, 0)); + vBox.setSpacing(2); vBox.getChildren().setAll(accountComboBox, titleLabel); parent.getChildren().add(vBox); - - accountComboBox.valueProperty().addListener((ov, oldValue, newValue) -> user.setCurrentBankAccount(newValue)); - } } - - } \ No newline at end of file diff --git a/src/main/java/io/bitsquare/gui/MainView.fxml b/src/main/java/io/bitsquare/gui/MainView.fxml index 23363a79df..72b7168b06 100644 --- a/src/main/java/io/bitsquare/gui/MainView.fxml +++ b/src/main/java/io/bitsquare/gui/MainView.fxml @@ -1,14 +1,16 @@ + - - - + + + + - + \ No newline at end of file diff --git a/src/main/java/io/bitsquare/gui/NavigationController.java b/src/main/java/io/bitsquare/gui/NavigationController.java index d383094d20..64b221b061 100644 --- a/src/main/java/io/bitsquare/gui/NavigationController.java +++ b/src/main/java/io/bitsquare/gui/NavigationController.java @@ -1,6 +1,10 @@ package io.bitsquare.gui; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + public interface NavigationController { - ChildController navigateToView(NavigationItem navigationItem); + @Nullable + ChildController navigateToView(@NotNull NavigationItem navigationItem); } diff --git a/src/main/java/io/bitsquare/gui/NavigationItem.java b/src/main/java/io/bitsquare/gui/NavigationItem.java index 3380a7cca1..89a19ce7d5 100644 --- a/src/main/java/io/bitsquare/gui/NavigationItem.java +++ b/src/main/java/io/bitsquare/gui/NavigationItem.java @@ -4,48 +4,45 @@ import io.bitsquare.gui.util.Icons; public enum NavigationItem { - MAIN("MAIN", "/io/bitsquare/gui/MainView.fxml"), - HOME("HOME", "/io/bitsquare/gui/home/HomeView.fxml", Icons.HOME, Icons.HOME_ACTIVE), - BUY("BUY", "/io/bitsquare/gui/market/MarketView.fxml", Icons.NAV_BUY, Icons.NAV_BUY_ACTIVE), - SELL("SELL", "/io/bitsquare/gui/market/MarketView.fxml", Icons.NAV_SELL, Icons.NAV_SELL_ACTIVE), - ORDERS("ORDERS", "/io/bitsquare/gui/orders/OrdersView.fxml", Icons.ORDERS, Icons.ORDERS_ACTIVE), - FUNDS("FUNDS", "/io/bitsquare/gui/funds/FundsView.fxml", Icons.FUNDS, Icons.FUNDS_ACTIVE), - MSG("MSG", "/io/bitsquare/gui/msg/MsgView.fxml", Icons.MSG, Icons.MSG_ACTIVE), - SETTINGS("SETTINGS", "/io/bitsquare/gui/settings/SettingsView.fxml", Icons.SETTINGS, Icons.SETTINGS_ACTIVE), + MAIN("/io/bitsquare/gui/MainView.fxml"), + HOME("/io/bitsquare/gui/home/HomeView.fxml", Icons.HOME, Icons.HOME_ACTIVE), + BUY("/io/bitsquare/gui/market/MarketView.fxml", Icons.NAV_BUY, Icons.NAV_BUY_ACTIVE), + SELL("/io/bitsquare/gui/market/MarketView.fxml", Icons.NAV_SELL, Icons.NAV_SELL_ACTIVE), + ORDERS("/io/bitsquare/gui/orders/OrdersView.fxml", Icons.ORDERS, Icons.ORDERS_ACTIVE), + FUNDS("/io/bitsquare/gui/funds/FundsView.fxml", Icons.FUNDS, Icons.FUNDS_ACTIVE), + MSG("/io/bitsquare/gui/msg/MsgView.fxml", Icons.MSG, Icons.MSG_ACTIVE), + SETTINGS("/io/bitsquare/gui/settings/SettingsView.fxml", Icons.SETTINGS, Icons.SETTINGS_ACTIVE), - ORDER_BOOK("ORDER_BOOK", "/io/bitsquare/gui/market/orderbook/OrderBookView.fxml"), - TAKER_TRADE("TAKER_TRADE", "/io/bitsquare/gui/market/trade/TakerTradeView.fxml"), - OFFERER_TRADE("OFFERER_TRADE", "/io/bitsquare/gui/orders/OffererTradeView.fxml"), - CREATE_OFFER("CREATE_OFFER", "/io/bitsquare/gui/market/createOffer/CreateOfferView.fxml"), + ORDER_BOOK("/io/bitsquare/gui/market/orderbook/OrderBookView.fxml"), + CREATE_OFFER("/io/bitsquare/gui/market/createOffer/CreateOfferView.fxml"), + TAKER_TRADE("/io/bitsquare/gui/market/trade/TakerTradeView.fxml"), + //OFFERER_TRADE("/io/bitsquare/gui/orders/OffererTradeView.fxml"), - CLOSED_TRADE("CLOSED_TRADE", "/io/bitsquare/gui/orders/closed/ClosedTradeView.fxml"), - OFFER("OFFER", "/io/bitsquare/gui/orders/offer/OfferView.fxml"), - PENDING_TRADE("PENDING_TRADE", "/io/bitsquare/gui/orders/pending/PendingTradeView.fxml"), + OFFER("/io/bitsquare/gui/orders/offer/OfferView.fxml"), + PENDING_TRADE("/io/bitsquare/gui/orders/pending/PendingTradeView.fxml"), + CLOSED_TRADE("/io/bitsquare/gui/orders/closed/ClosedTradeView.fxml"), - DEPOSIT("DEPOSIT", "/io/bitsquare/gui/funds/deposit/DepositView.fxml"), - WITHDRAWAL("WITHDRAWAL", "/io/bitsquare/gui/funds/withdrawal/WithdrawalView.fxml"), - TRANSACTIONS("TRANSACTIONS", "/io/bitsquare/gui/funds/transactions/TransactionsView.fxml"), + DEPOSIT("/io/bitsquare/gui/funds/deposit/DepositView.fxml"), + WITHDRAWAL("/io/bitsquare/gui/funds/withdrawal/WithdrawalView.fxml"), + TRANSACTIONS("/io/bitsquare/gui/funds/transactions/TransactionsView.fxml"), - ARBITRATOR_PROFILE("ARBITRATOR_PROFILE", "/io/bitsquare/gui/arbitrators/profile/ArbitratorProfileView.fxml"), - ARBITRATOR_OVERVIEW("ARBITRATOR_OVERVIEW", "/io/bitsquare/gui/arbitrators/overview/ArbitratorOverviewView.fxml"), - ARBITRATOR_REGISTRATION("ARBITRATOR_REGISTRATION", "/io/bitsquare/gui/arbitrators/registration/ArbitratorRegistrationView.fxml"); + ARBITRATOR_PROFILE("/io/bitsquare/gui/arbitrators/profile/ArbitratorProfileView.fxml"), + ARBITRATOR_OVERVIEW("/io/bitsquare/gui/arbitrators/overview/ArbitratorOverviewView.fxml"), + ARBITRATOR_REGISTRATION("/io/bitsquare/gui/arbitrators/registration/ArbitratorRegistrationView.fxml"); - private String fxmlUrl; - private String id; + private final String fxmlUrl; private String icon; private String activeIcon; - NavigationItem(String id, String fxmlUrl, String icon, String activeIcon) + NavigationItem(String fxmlUrl, String icon, String activeIcon) { - this.id = id; this.fxmlUrl = fxmlUrl; this.icon = icon; this.activeIcon = activeIcon; } - NavigationItem(String id, String fxmlUrl) + NavigationItem(String fxmlUrl) { - this.id = id; this.fxmlUrl = fxmlUrl; } @@ -54,11 +51,6 @@ public enum NavigationItem return fxmlUrl; } - public String getId() - { - return id; - } - public String getIcon() { return icon; diff --git a/src/main/java/io/bitsquare/gui/arbitrators/overview/ArbitratorOverviewController.java b/src/main/java/io/bitsquare/gui/arbitrators/overview/ArbitratorOverviewController.java index 039d208418..1fc04f0a4f 100644 --- a/src/main/java/io/bitsquare/gui/arbitrators/overview/ArbitratorOverviewController.java +++ b/src/main/java/io/bitsquare/gui/arbitrators/overview/ArbitratorOverviewController.java @@ -29,11 +29,15 @@ import javafx.scene.layout.Pane; import javafx.stage.Stage; import net.tomp2p.peers.Number160; import net.tomp2p.storage.Data; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +@SuppressWarnings({"ALL", "UnusedParameters"}) public class ArbitratorOverviewController implements Initializable, ChildController, NavigationController, ArbitratorListener { private final Settings settings; private final Storage storage; + @NotNull private final MessageFacade messageFacade; private final List allArbitrators = new ArrayList<>(); private Arbitrator currentArbitrator; @@ -53,7 +57,7 @@ public class ArbitratorOverviewController implements Initializable, ChildControl /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public ArbitratorOverviewController(Settings settings, Storage storage, MessageFacade messageFacade) + public ArbitratorOverviewController(Settings settings, Storage storage, @NotNull MessageFacade messageFacade) { this.settings = settings; @@ -82,7 +86,7 @@ public class ArbitratorOverviewController implements Initializable, ChildControl /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { this.navigationController = navigationController; } @@ -98,13 +102,14 @@ public class ArbitratorOverviewController implements Initializable, ChildControl // Interface implementation: NavigationController /////////////////////////////////////////////////////////////////////////////////////////// + @Nullable @Override - public ChildController navigateToView(NavigationItem navigationItem) + public ChildController navigateToView(@NotNull NavigationItem navigationItem) { if (arbitratorProfileController != null) arbitratorProfileController.cleanup(); - final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); + @NotNull final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); try { final Node view = loader.load(); @@ -131,23 +136,23 @@ public class ArbitratorOverviewController implements Initializable, ChildControl } @Override - public void onArbitratorsReceived(Map dataMap, boolean success) + public void onArbitratorsReceived(@Nullable Map dataMap, boolean success) { if (success && dataMap != null) { allArbitrators.clear(); - for (Data arbitratorData : dataMap.values()) + for (@NotNull Data arbitratorData : dataMap.values()) { try { Object arbitratorDataObject = arbitratorData.getObject(); - if (arbitratorDataObject instanceof Arbitrator && arbitratorDataObject != null) + if (arbitratorDataObject instanceof Arbitrator) { - Arbitrator arbitrator = (Arbitrator) arbitratorDataObject; + @NotNull Arbitrator arbitrator = (Arbitrator) arbitratorDataObject; allArbitrators.add(arbitrator); } - } catch (ClassNotFoundException | IOException e) + } catch (@NotNull ClassNotFoundException | IOException e) { e.printStackTrace(); } @@ -158,7 +163,7 @@ public class ArbitratorOverviewController implements Initializable, ChildControl allArbitrators.clear(); } - if (allArbitrators.size() > 0) + if (!allArbitrators.isEmpty()) { index = 0; currentArbitrator = allArbitrators.get(index); @@ -211,7 +216,7 @@ public class ArbitratorOverviewController implements Initializable, ChildControl @FXML public void onClose(ActionEvent actionEvent) { - Stage stage = (Stage) rootContainer.getScene().getWindow(); + @NotNull Stage stage = (Stage) rootContainer.getScene().getWindow(); stage.close(); } diff --git a/src/main/java/io/bitsquare/gui/arbitrators/profile/ArbitratorProfileController.java b/src/main/java/io/bitsquare/gui/arbitrators/profile/ArbitratorProfileController.java index 98f069fabb..f926483dbe 100644 --- a/src/main/java/io/bitsquare/gui/arbitrators/profile/ArbitratorProfileController.java +++ b/src/main/java/io/bitsquare/gui/arbitrators/profile/ArbitratorProfileController.java @@ -14,10 +14,15 @@ import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +@SuppressWarnings("ALL") public class ArbitratorProfileController implements Initializable, ChildController { + @NotNull private final Settings settings; + @NotNull private final Storage storage; private Arbitrator arbitrator; private NavigationController navigationController; @@ -36,15 +41,13 @@ public class ArbitratorProfileController implements Initializable, ChildControll /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public ArbitratorProfileController(Settings settings, Storage storage) + public ArbitratorProfileController(@NotNull Settings settings, @NotNull Storage storage) { - this.settings = settings; this.storage = storage; - Settings savedSettings = (Settings) storage.read(settings.getClass().getName()); - if (savedSettings != null) - settings.updateFromStorage(savedSettings); + // @NotNull Settings savedSettings = (Settings) storage.read(settings.getClass().getName()); + // settings.updateFromStorage(savedSettings); } @@ -52,11 +55,11 @@ public class ArbitratorProfileController implements Initializable, ChildControll // Public Methods /////////////////////////////////////////////////////////////////////////////////////////// - public void applyArbitrator(Arbitrator arbitrator) + public void applyArbitrator(@Nullable Arbitrator arbitrator) { if (arbitrator != null) { - String name = ""; + @NotNull String name = ""; switch (arbitrator.getIdType()) { case REAL_LIFE_ID: @@ -99,7 +102,7 @@ public class ArbitratorProfileController implements Initializable, ChildControll /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { this.navigationController = navigationController; } diff --git a/src/main/java/io/bitsquare/gui/arbitrators/registration/ArbitratorRegistrationController.java b/src/main/java/io/bitsquare/gui/arbitrators/registration/ArbitratorRegistrationController.java index 261e78028c..0e5530bab1 100644 --- a/src/main/java/io/bitsquare/gui/arbitrators/registration/ArbitratorRegistrationController.java +++ b/src/main/java/io/bitsquare/gui/arbitrators/registration/ArbitratorRegistrationController.java @@ -38,9 +38,12 @@ import javafx.scene.input.ClipboardContent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.util.StringConverter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings({"ALL", "EmptyMethod", "UnusedParameters"}) public class ArbitratorRegistrationController implements Initializable, ChildController { private static final Logger log = LoggerFactory.getLogger(ArbitratorRegistrationController.class); @@ -48,11 +51,14 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon private final Storage storage; private final WalletFacade walletFacade; private final MessageFacade messageFacade; - private Arbitrator arbitrator; + private Arbitrator arbitrator = new Arbitrator(); private ArbitratorProfileController arbitratorProfileController; private boolean isEditMode; + @NotNull private List languageList = new ArrayList<>(); + @NotNull private List methodList = new ArrayList<>(); + @NotNull private List idVerificationList = new ArrayList<>(); private Arbitrator.ID_TYPE idType; private ConfidenceDisplay confidenceDisplay; @@ -89,7 +95,7 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public ArbitratorRegistrationController(Storage storage, WalletFacade walletFacade, MessageFacade messageFacade) + private ArbitratorRegistrationController(Storage storage, WalletFacade walletFacade, MessageFacade messageFacade) { this.storage = storage; this.walletFacade = walletFacade; @@ -101,7 +107,7 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon // Public Methods /////////////////////////////////////////////////////////////////////////////////////////// - public void setEditMode(boolean isEditMode) + public void setEditMode(@SuppressWarnings("SameParameterValue") boolean isEditMode) { this.isEditMode = isEditMode; @@ -123,7 +129,6 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon { accordion.setExpandedPane(profileTitledPane); - arbitrator = new Arbitrator(); Arbitrator savedArbitrator = (Arbitrator) storage.read(arbitrator.getClass().getName()); if (savedArbitrator != null) { @@ -140,11 +145,12 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon languageComboBox.setConverter(new StringConverter() { @Override - public String toString(Locale locale) + public String toString(@NotNull Locale locale) { return locale.getDisplayLanguage(); } + @Nullable @Override public Locale fromString(String s) { @@ -155,12 +161,14 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon idTypeComboBox.setItems(FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator.ID_TYPE.class)))); idTypeComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(Arbitrator.ID_TYPE item) + public String toString(@NotNull Arbitrator.ID_TYPE item) { return Localisation.get(item.toString()); } + @Nullable @Override public Arbitrator.ID_TYPE fromString(String s) { @@ -171,12 +179,14 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon methodsComboBox.setItems(FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator.METHOD.class)))); methodsComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(Arbitrator.METHOD item) + public String toString(@NotNull Arbitrator.METHOD item) { return Localisation.get(item.toString()); } + @Nullable @Override public Arbitrator.METHOD fromString(String s) { @@ -187,12 +197,14 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon idVerificationsComboBox.setItems(FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator.ID_VERIFICATION.class)))); idVerificationsComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(Arbitrator.ID_VERIFICATION item) + public String toString(@NotNull Arbitrator.ID_VERIFICATION item) { return Localisation.get(item.toString()); } + @Nullable @Override public Arbitrator.ID_VERIFICATION fromString(String s) { @@ -207,7 +219,7 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { } @@ -229,7 +241,7 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon { idTypeTextField.setText(Localisation.get(idType.toString())); - String name = ""; + @NotNull String name = ""; switch (idType) { case REAL_LIFE_ID: @@ -358,24 +370,25 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon "depending on the overall relation of negative to positive ratings you received after a dispute resolution.\n\n" + "Please pay in " + arbitrator.getMaxTradeVolume() * 10 + " BTC"); - String collateralAddress = walletFacade.getRegistrationAddressInfo().toString(); + + String collateralAddress = walletFacade.getRegistrationAddressInfo() != null ? walletFacade.getRegistrationAddressInfo().toString() : ""; collateralAddressTextField.setText(collateralAddress); AwesomeDude.setIcon(copyIcon, AwesomeIcon.COPY); copyIcon.setOnMouseClicked(e -> { Clipboard clipboard = Clipboard.getSystemClipboard(); - ClipboardContent content = new ClipboardContent(); + @NotNull ClipboardContent content = new ClipboardContent(); content.putString(collateralAddress); clipboard.setContent(content); }); confidenceDisplay = new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, balanceTextField, progressIndicator); paymentDoneButton.setDisable(walletFacade.getArbitratorDepositBalance().compareTo(BigInteger.ZERO) == 0); - log.debug("getArbitratorDepositBalance " + walletFacade.getArbitratorDepositBalance().toString()); + log.debug("getArbitratorDepositBalance " + walletFacade.getArbitratorDepositBalance()); walletFacade.getWallet().addEventListener(new WalletEventListener() { @Override - public void onCoinsReceived(Wallet wallet, Transaction tx, BigInteger prevBalance, BigInteger newBalance) + public void onCoinsReceived(Wallet wallet, Transaction tx, BigInteger prevBalance, @NotNull BigInteger newBalance) { paymentDoneButton.setDisable(newBalance.compareTo(BigInteger.ZERO) == 0); } @@ -416,7 +429,7 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon { if (arbitrator != null) { - String name = ""; + @NotNull String name = ""; switch (arbitrator.getIdType()) { case REAL_LIFE_ID: @@ -451,6 +464,7 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon } } + @Nullable private Arbitrator getEditedArbitrator() { try @@ -494,7 +508,7 @@ public class ArbitratorRegistrationController implements Initializable, ChildCon private void close() { - Stage stage = (Stage) rootContainer.getScene().getWindow(); + @NotNull Stage stage = (Stage) rootContainer.getScene().getWindow(); stage.close(); } diff --git a/src/main/java/io/bitsquare/gui/bitsquare.css b/src/main/java/io/bitsquare/gui/bitsquare.css index 51327038cc..be87fffb36 100644 --- a/src/main/java/io/bitsquare/gui/bitsquare.css +++ b/src/main/java/io/bitsquare/gui/bitsquare.css @@ -158,7 +158,7 @@ #form-entry-value { } -/* tabpane */ +/* tab pane */ .tab-pane .tab-label { -fx-font-size: 15; } diff --git a/src/main/java/io/bitsquare/gui/components/HSpacer.java b/src/main/java/io/bitsquare/gui/components/HSpacer.java index 479e51002e..71b9d1079b 100644 --- a/src/main/java/io/bitsquare/gui/components/HSpacer.java +++ b/src/main/java/io/bitsquare/gui/components/HSpacer.java @@ -3,13 +3,14 @@ package io.bitsquare.gui.components; import javafx.scene.layout.Pane; +@SuppressWarnings("WeakerAccess") public class HSpacer extends Pane { public HSpacer() { } - public HSpacer(double width) + public HSpacer(@SuppressWarnings("SameParameterValue") double width) { setPrefWidth(width); } diff --git a/src/main/java/io/bitsquare/gui/components/LazyLoadingTabPane.java b/src/main/java/io/bitsquare/gui/components/LazyLoadingTabPane.java index d3d070f8d7..548cc7fede 100644 --- a/src/main/java/io/bitsquare/gui/components/LazyLoadingTabPane.java +++ b/src/main/java/io/bitsquare/gui/components/LazyLoadingTabPane.java @@ -13,12 +13,14 @@ import javafx.scene.Node; import javafx.scene.control.SingleSelectionModel; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class LazyLoadingTabPane extends TabPane { private final Map views = new HashMap<>(); private final Map controllers = new HashMap<>(); - SingleSelectionModel selectionModel; + private SingleSelectionModel selectionModel; private String storageId; private NavigationController navigationController; private String[] tabContentFXMLUrls; @@ -35,7 +37,7 @@ public class LazyLoadingTabPane extends TabPane super(); } - public void initialize(NavigationController navigationController, Storage storage, String... tabContentFXMLUrls) + public void initialize(@NotNull NavigationController navigationController, @NotNull Storage storage, @NotNull String... tabContentFXMLUrls) { if (tabContentFXMLUrls.length == 0) throw new IllegalArgumentException("No tabContentFXMLUrls defined"); @@ -63,6 +65,7 @@ public class LazyLoadingTabPane extends TabPane childController.cleanup(); } + @Nullable public ChildController navigateToView(String fxmlView) { for (int i = 0; i < tabContentFXMLUrls.length; i++) @@ -85,7 +88,7 @@ public class LazyLoadingTabPane extends TabPane if (childController != null) ((Hibernate) childController).sleep(); - Node view = null; + @Nullable Node view = null; if (index < views.size()) { view = views.get(index); @@ -94,7 +97,7 @@ public class LazyLoadingTabPane extends TabPane if (view == null) { String fxmlView = tabContentFXMLUrls[index]; - final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(fxmlView), Localisation.getResourceBundle()); + @NotNull final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(fxmlView), Localisation.getResourceBundle()); try { view = loader.load(); diff --git a/src/main/java/io/bitsquare/gui/components/NetworkSyncPane.java b/src/main/java/io/bitsquare/gui/components/NetworkSyncPane.java index 041ccf4fae..6f190c88b4 100644 --- a/src/main/java/io/bitsquare/gui/components/NetworkSyncPane.java +++ b/src/main/java/io/bitsquare/gui/components/NetworkSyncPane.java @@ -6,10 +6,13 @@ import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.layout.HBox; import javafx.util.Duration; +import org.jetbrains.annotations.NotNull; public class NetworkSyncPane extends HBox { + @NotNull private final ProgressBar networkSyncProgressBar; + @NotNull private final Label networkSyncInfoLabel; public NetworkSyncPane() @@ -34,7 +37,7 @@ public class NetworkSyncPane extends HBox networkSyncInfoLabel.setText("Sync with network: Done"); networkSyncProgressBar.setProgress(1); - FadeTransition fade = new FadeTransition(Duration.millis(700), this); + @NotNull FadeTransition fade = new FadeTransition(Duration.millis(700), this); fade.setToValue(0.0); fade.setCycleCount(1); fade.setInterpolator(Interpolator.EASE_BOTH); diff --git a/src/main/java/io/bitsquare/gui/components/NoFocusScrollPane.java b/src/main/java/io/bitsquare/gui/components/NoFocusScrollPane.java index 59251ae266..a5cef0f92c 100644 --- a/src/main/java/io/bitsquare/gui/components/NoFocusScrollPane.java +++ b/src/main/java/io/bitsquare/gui/components/NoFocusScrollPane.java @@ -2,7 +2,7 @@ package io.bitsquare.gui.components; import javafx.scene.control.ScrollPane; -public class NoFocusScrollPane extends ScrollPane +class NoFocusScrollPane extends ScrollPane { public NoFocusScrollPane() { diff --git a/src/main/java/io/bitsquare/gui/components/VSpacer.java b/src/main/java/io/bitsquare/gui/components/VSpacer.java index d0dc7f339a..500732e67b 100644 --- a/src/main/java/io/bitsquare/gui/components/VSpacer.java +++ b/src/main/java/io/bitsquare/gui/components/VSpacer.java @@ -9,6 +9,7 @@ public class VSpacer extends Pane { } + @SuppressWarnings("SameParameterValue") public VSpacer(double height) { setPrefHeight(height); diff --git a/src/main/java/io/bitsquare/gui/components/confidence/ConfidenceProgressIndicator.java b/src/main/java/io/bitsquare/gui/components/confidence/ConfidenceProgressIndicator.java index f5e6386689..1a5fbfa164 100644 --- a/src/main/java/io/bitsquare/gui/components/confidence/ConfidenceProgressIndicator.java +++ b/src/main/java/io/bitsquare/gui/components/confidence/ConfidenceProgressIndicator.java @@ -34,6 +34,7 @@ import javafx.css.PseudoClass; import javafx.css.StyleableProperty; import javafx.scene.control.Control; import javafx.scene.control.Skin; +import org.jetbrains.annotations.NotNull; /** @@ -64,6 +65,7 @@ import javafx.scene.control.Skin; * @since JavaFX 2.0 */ +@SuppressWarnings({"SameParameterValue", "WeakerAccess"}) public class ConfidenceProgressIndicator extends Control { @@ -175,12 +177,14 @@ public class ConfidenceProgressIndicator extends Control pseudoClassStateChanged(PSEUDO_CLASS_DETERMINATE, !active); } + @NotNull @Override public Object getBean() { return ConfidenceProgressIndicator.this; } + @NotNull @Override public String getName() { @@ -229,12 +233,14 @@ public class ConfidenceProgressIndicator extends Control setIndeterminate(getProgress() < 0.0); } + @NotNull @Override public Object getBean() { return ConfidenceProgressIndicator.this; } + @NotNull @Override public String getName() { @@ -248,6 +254,7 @@ public class ConfidenceProgressIndicator extends Control /** * {@inheritDoc} */ + @NotNull @Override protected Skin createDefaultSkin() { @@ -259,8 +266,6 @@ public class ConfidenceProgressIndicator extends Control * this method to return true, but ProgressIndicator returns false for * focusTraversable's initial value; hence the override of the override. * This method is called from CSS code to get the correct initial value. - * - * @treatAsPrivate implementation detail */ @Deprecated @Override diff --git a/src/main/java/io/bitsquare/gui/components/confidence/skin/ConfidenceProgressIndicatorSkin.java b/src/main/java/io/bitsquare/gui/components/confidence/skin/ConfidenceProgressIndicatorSkin.java index 67f286362b..b7ef4af93b 100644 --- a/src/main/java/io/bitsquare/gui/components/confidence/skin/ConfidenceProgressIndicatorSkin.java +++ b/src/main/java/io/bitsquare/gui/components/confidence/skin/ConfidenceProgressIndicatorSkin.java @@ -59,7 +59,10 @@ import javafx.scene.shape.ArcType; import javafx.scene.shape.Circle; import javafx.scene.transform.Scale; import javafx.util.Duration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +@SuppressWarnings({"WeakerAccess", "SameReturnValue"}) public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase> { @@ -81,10 +84,12 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase getCssMetaData() { @@ -116,6 +124,7 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase getCssMetaData() { return StyleableProperties.SPIN_ENABLED; } + @NotNull @Override public Object getBean() { return ConfidenceProgressIndicatorSkin.this; } + @NotNull @Override public String getName() { return "spinEnabled"; } }; + @Nullable private DeterminateIndicator determinateIndicator; /** * The colour of the progress segment. */ + @Nullable private final ObjectProperty progressColor = new StyleableObjectProperty(null) { @@ -153,7 +167,7 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase getCssMetaData() { @@ -194,14 +211,14 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase(control)); - InvalidationListener indeterminateListener = valueModel -> initialize(); + @NotNull InvalidationListener indeterminateListener = valueModel -> initialize(); control.indeterminateProperty().addListener(indeterminateListener); - InvalidationListener visibilityListener = new InvalidationListener() + @NotNull InvalidationListener visibilityListener = new InvalidationListener() { @Override public void invalidated(Observable valueModel) @@ -232,7 +249,7 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase updateProgress(); + @NotNull InvalidationListener progressListener = valueModel -> updateProgress(); control.progressProperty().addListener(progressListener); getChildren().clear(); @@ -430,7 +454,7 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase opacities = new ArrayList<>(); private boolean spinEnabled = false; + @Nullable private Paint fillOverride = null; - public IndeterminateSpinner(ConfidenceProgressIndicator control, ConfidenceProgressIndicatorSkin s, boolean spinEnabled, Paint fillOverride) + public IndeterminateSpinner(ConfidenceProgressIndicator control, ConfidenceProgressIndicatorSkin s, boolean spinEnabled, @Nullable Paint fillOverride) { this.control = control; this.skin = s; @@ -632,7 +660,7 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase { + @NotNull InvalidationListener treeVisibilityListener = valueModel -> { if (piSkin.skin.getSkinnable().impl_isTreeVisible()) { piSkin.pauseIndicator(false); @@ -763,7 +791,7 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase child instanceof Region).forEach(child -> { - Region region = (Region) child; + @NotNull Region region = (Region) child; if (region.getShape() != null) { region.resize( @@ -825,83 +853,87 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase> STYLEABLES; + @Nullable private static final CssMetaData PROGRESS_COLOR = new CssMetaData("-fx-progress-color", PaintConverter.getInstance(), null) { @Override - public boolean isSettable(ConfidenceProgressIndicator n) + public boolean isSettable(@NotNull ConfidenceProgressIndicator n) { - final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); + @NotNull final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); return skin.progressColor == null || !skin.progressColor.isBound(); } + @Nullable @Override - public StyleableProperty getStyleableProperty(ConfidenceProgressIndicator n) + public StyleableProperty getStyleableProperty(@NotNull ConfidenceProgressIndicator n) { - final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); + @NotNull final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); return (StyleableProperty) skin.progressColor; } }; + @Nullable private static final CssMetaData INDETERMINATE_SEGMENT_COUNT = new CssMetaData("-fx-indeterminate-segment-count", SizeConverter.getInstance(), 8) { @Override - public void set(ConfidenceProgressIndicator node, Number value, StyleOrigin origin) + public void set(ConfidenceProgressIndicator node, @NotNull Number value, StyleOrigin origin) { super.set(node, value.intValue(), origin); } @Override - public boolean isSettable(ConfidenceProgressIndicator n) + public boolean isSettable(@NotNull ConfidenceProgressIndicator n) { - final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); + @NotNull final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); return skin.indeterminateSegmentCount == null || !skin.indeterminateSegmentCount.isBound(); } + @Nullable @Override - public StyleableProperty getStyleableProperty(ConfidenceProgressIndicator n) + public StyleableProperty getStyleableProperty(@NotNull ConfidenceProgressIndicator n) { - final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); + @NotNull final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); return (StyleableProperty) skin.indeterminateSegmentCount; } }; + @Nullable private static final CssMetaData SPIN_ENABLED = new CssMetaData("-fx-spin-enabled", BooleanConverter.getInstance(), Boolean.FALSE) { @Override - public boolean isSettable(ConfidenceProgressIndicator node) + public boolean isSettable(@NotNull ConfidenceProgressIndicator node) { - final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin(); + @NotNull final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin(); return skin.spinEnabled == null || !skin.spinEnabled.isBound(); } + @Nullable @Override - public StyleableProperty getStyleableProperty(ConfidenceProgressIndicator node) + public StyleableProperty getStyleableProperty(@NotNull ConfidenceProgressIndicator node) { - final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin(); + @NotNull final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin(); return (StyleableProperty) skin.spinEnabled; } }; static { - final List> styleables = new ArrayList<>(SkinBase.getClassCssMetaData()); + @NotNull final List> styleables = new ArrayList<>(SkinBase.getClassCssMetaData()); styleables.add(PROGRESS_COLOR); styleables.add(INDETERMINATE_SEGMENT_COUNT); styleables.add(SPIN_ENABLED); diff --git a/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBar.java b/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBar.java index 658f7ec8b9..eba12db2d2 100644 --- a/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBar.java +++ b/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBar.java @@ -3,11 +3,14 @@ package io.bitsquare.gui.components.processbar; import java.util.List; import javafx.scene.control.Control; import javafx.scene.control.Skin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class ProcessStepBar extends Control { + @Nullable private List processStepItems = null; public ProcessStepBar() @@ -15,23 +18,25 @@ public class ProcessStepBar extends Control } - public ProcessStepBar(List processStepItems) + public ProcessStepBar(@Nullable List processStepItems) { this.processStepItems = processStepItems; } + @NotNull @Override protected Skin createDefaultSkin() { return new ProcessStepBarSkin<>(this); } + @Nullable List getProcessStepItems() { return processStepItems; } - public void setProcessStepItems(List processStepItems) + public void setProcessStepItems(@Nullable List processStepItems) { this.processStepItems = processStepItems; if (getSkin() != null) diff --git a/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBarSkin.java b/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBarSkin.java index 1c3df0c6ba..ab0a4d222d 100644 --- a/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBarSkin.java +++ b/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepBarSkin.java @@ -16,15 +16,15 @@ import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.paint.Color; import javafx.scene.shape.*; +import org.jetbrains.annotations.NotNull; - -public class ProcessStepBarSkin extends BehaviorSkinBase, BehaviorBase>> +class ProcessStepBarSkin extends BehaviorSkinBase, BehaviorBase>> { - final ProcessStepBar controller; - LabelWithBorder currentLabelWithBorder; - LabelWithBorder prevLabelWithBorder; - int index; - List labelWithBorders; + private final ProcessStepBar controller; + private LabelWithBorder currentLabelWithBorder; + private LabelWithBorder prevLabelWithBorder; + private int index; + private List labelWithBorders; public ProcessStepBarSkin(final ProcessStepBar control) { @@ -47,9 +47,9 @@ public class ProcessStepBarSkin extends BehaviorSkinBase, B int i = 0; labelWithBorders = new ArrayList<>(); int size = controller.getProcessStepItems().size(); - for (ProcessStepItem processStepItem : controller.getProcessStepItems()) + for (@NotNull ProcessStepItem processStepItem : controller.getProcessStepItems()) { - LabelWithBorder labelWithBorder = new LabelWithBorder(processStepItem, i == 0, i == size - 1); + @NotNull LabelWithBorder labelWithBorder = new LabelWithBorder(processStepItem, i == 0, i == size - 1); getChildren().add(labelWithBorder); labelWithBorders.add(labelWithBorder); if (i == 0) @@ -100,16 +100,18 @@ public class ProcessStepBarSkin extends BehaviorSkinBase, B } + @SuppressWarnings("EmptyMethod") public static class LabelWithBorder extends Label { final double borderWidth = 1; private final double arrowWidth = 10; private final double arrowHeight = 30; + @NotNull private final ProcessStepItem processStepItem; private final boolean isFirst; private final boolean isLast; - public LabelWithBorder(ProcessStepItem processStepItem, boolean isFirst, boolean isLast) + public LabelWithBorder(@NotNull ProcessStepItem processStepItem, boolean isFirst, boolean isLast) { super(processStepItem.getLabel()); this.processStepItem = processStepItem; @@ -123,14 +125,14 @@ public class ProcessStepBarSkin extends BehaviorSkinBase, B this.setShape(createButtonShape()); - BorderStroke borderStroke = new BorderStroke(Color.LIGHTGRAY, BorderStrokeStyle.SOLID, null, + @NotNull BorderStroke borderStroke = new BorderStroke(Color.LIGHTGRAY, BorderStrokeStyle.SOLID, null, new BorderWidths(borderWidth, borderWidth, borderWidth, borderWidth), Insets.EMPTY); this.setBorder(new Border(borderStroke)); } public void select() { - BorderStroke borderStroke = new BorderStroke(processStepItem.getColor(), BorderStrokeStyle.SOLID, null, + @NotNull BorderStroke borderStroke = new BorderStroke(processStepItem.getColor(), BorderStrokeStyle.SOLID, null, new BorderWidths(borderWidth, borderWidth, borderWidth, borderWidth), Insets.EMPTY); this.setBorder(new Border(borderStroke)); setTextFill(processStepItem.getColor()); @@ -150,6 +152,7 @@ public class ProcessStepBarSkin extends BehaviorSkinBase, B return arrowWidth; } + @NotNull private Path createButtonShape() { // build the following shape (or home without left arrow) @@ -158,14 +161,14 @@ public class ProcessStepBarSkin extends BehaviorSkinBase, B // \ \ // / / // -------- - Path path = new Path(); + @NotNull Path path = new Path(); // begin in the upper left corner - MoveTo e1 = new MoveTo(0, 0); + @NotNull MoveTo e1 = new MoveTo(0, 0); path.getElements().add(e1); // draw a horizontal line that defines the width of the shape - HLineTo e2 = new HLineTo(); + @NotNull HLineTo e2 = new HLineTo(); // bind the width of the shape to the width of the button e2.xProperty().bind(this.widthProperty().subtract(arrowWidth)); path.getElements().add(e2); @@ -173,7 +176,7 @@ public class ProcessStepBarSkin extends BehaviorSkinBase, B if (!isLast) { // draw upper part of right arrow - LineTo e3 = new LineTo(); + @NotNull LineTo e3 = new LineTo(); // the x endpoint of this line depends on the x property of line e2 e3.xProperty().bind(e2.xProperty().add(arrowWidth)); e3.setY(arrowHeight / 2.0); @@ -182,24 +185,24 @@ public class ProcessStepBarSkin extends BehaviorSkinBase, B // draw lower part of right arrow - LineTo e4 = new LineTo(); + @NotNull LineTo e4 = new LineTo(); // the x endpoint of this line depends on the x property of line e2 e4.xProperty().bind(e2.xProperty()); e4.setY(arrowHeight); path.getElements().add(e4); // draw lower horizontal line - HLineTo e5 = new HLineTo(0); + @NotNull HLineTo e5 = new HLineTo(0); path.getElements().add(e5); if (!isFirst) { - LineTo e6 = new LineTo(arrowWidth, arrowHeight / 2.0); + @NotNull LineTo e6 = new LineTo(arrowWidth, arrowHeight / 2.0); path.getElements().add(e6); } // close path - ClosePath e7 = new ClosePath(); + @NotNull ClosePath e7 = new ClosePath(); path.getElements().add(e7); // this is a dummy color to fill the shape, it won't be visible path.setFill(Color.BLACK); diff --git a/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepItem.java b/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepItem.java index ee534d83bc..c0ba6bbe42 100644 --- a/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepItem.java +++ b/src/main/java/io/bitsquare/gui/components/processbar/ProcessStepItem.java @@ -19,7 +19,7 @@ public class ProcessStepItem this(label, color, false); } - public ProcessStepItem(String label, Paint color, boolean hasProgressIndicator) + private ProcessStepItem(String label, Paint color, @SuppressWarnings("SameParameterValue") boolean hasProgressIndicator) { this.label = label; this.color = color; diff --git a/src/main/java/io/bitsquare/gui/funds/FundsController.java b/src/main/java/io/bitsquare/gui/funds/FundsController.java index 4e224645e1..c085f6e3d6 100644 --- a/src/main/java/io/bitsquare/gui/funds/FundsController.java +++ b/src/main/java/io/bitsquare/gui/funds/FundsController.java @@ -10,6 +10,7 @@ import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,7 +28,7 @@ public class FundsController implements Initializable, ChildController, Navigati /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public FundsController(Storage storage) + private FundsController(Storage storage) { this.storage = storage; } @@ -49,7 +50,7 @@ public class FundsController implements Initializable, ChildController, Navigati /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { } @@ -64,7 +65,7 @@ public class FundsController implements Initializable, ChildController, Navigati /////////////////////////////////////////////////////////////////////////////////////////// @Override - public ChildController navigateToView(NavigationItem navigationItem) + public ChildController navigateToView(@NotNull NavigationItem navigationItem) { return tabPane.navigateToView(navigationItem.getFxmlUrl()); } diff --git a/src/main/java/io/bitsquare/gui/funds/deposit/DepositController.java b/src/main/java/io/bitsquare/gui/funds/deposit/DepositController.java index e8ec088790..bb214fcdca 100644 --- a/src/main/java/io/bitsquare/gui/funds/deposit/DepositController.java +++ b/src/main/java/io/bitsquare/gui/funds/deposit/DepositController.java @@ -11,16 +11,18 @@ import io.bitsquare.gui.NavigationController; import java.net.URL; import java.util.List; import java.util.ResourceBundle; +import java.util.stream.Collectors; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.util.Callback; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,7 +31,7 @@ public class DepositController implements Initializable, ChildController, Hibern private static final Logger log = LoggerFactory.getLogger(DepositController.class); private final WalletFacade walletFacade; - protected ObservableList addressList; + private ObservableList addressList; @FXML private TableView tableView; @@ -44,7 +46,7 @@ public class DepositController implements Initializable, ChildController, Hibern /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public DepositController(WalletFacade walletFacade) + private DepositController(WalletFacade walletFacade) { this.walletFacade = walletFacade; } @@ -72,14 +74,14 @@ public class DepositController implements Initializable, ChildController, Hibern /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { } @Override public void cleanup() { - for (DepositListItem anAddressList : addressList) + for (@NotNull DepositListItem anAddressList : addressList) { anAddressList.cleanup(); } @@ -101,10 +103,7 @@ public class DepositController implements Initializable, ChildController, Hibern { List addressEntryList = walletFacade.getAddressEntryList(); addressList = FXCollections.observableArrayList(); - for (AddressEntry anAddressEntryList : addressEntryList) - { - addressList.add(new DepositListItem(anAddressEntryList, walletFacade)); - } + addressList.addAll(addressEntryList.stream().map(anAddressEntryList -> new DepositListItem(anAddressEntryList, walletFacade)).collect(Collectors.toList())); tableView.setItems(addressList); } @@ -115,7 +114,7 @@ public class DepositController implements Initializable, ChildController, Hibern /////////////////////////////////////////////////////////////////////////////////////////// @FXML - public void onAddNewTradeAddress(ActionEvent actionEvent) + public void onAddNewTradeAddress() { addressList.add(new DepositListItem(walletFacade.getNewTradeAddressEntry(), walletFacade)); } @@ -135,15 +134,17 @@ public class DepositController implements Initializable, ChildController, Hibern labelColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); labelColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { return new TableCell() { + @Nullable Hyperlink hyperlink; @Override - public void updateItem(final DepositListItem item, boolean empty) + public void updateItem(@Nullable final DepositListItem item, boolean empty) { super.updateItem(item, empty); @@ -153,7 +154,7 @@ public class DepositController implements Initializable, ChildController, Hibern hyperlink.setId("id-link"); if (item.getAddressEntry().getTradeId() != null) { - Tooltip tooltip = new Tooltip(item.getAddressEntry().getTradeId()); + @NotNull Tooltip tooltip = new Tooltip(item.getAddressEntry().getTradeId()); Tooltip.install(hyperlink, tooltip); hyperlink.setOnAction(event -> log.info("Show trade details " + item.getAddressEntry().getTradeId())); @@ -176,13 +177,14 @@ public class DepositController implements Initializable, ChildController, Hibern balanceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); balanceColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { return new TableCell() { @Override - public void updateItem(final DepositListItem item, boolean empty) + public void updateItem(@Nullable final DepositListItem item, boolean empty) { super.updateItem(item, empty); @@ -205,6 +207,7 @@ public class DepositController implements Initializable, ChildController, Hibern copyColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); copyColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { @@ -219,7 +222,7 @@ public class DepositController implements Initializable, ChildController, Hibern } @Override - public void updateItem(final DepositListItem item, boolean empty) + public void updateItem(@Nullable final DepositListItem item, boolean empty) { super.updateItem(item, empty); @@ -228,7 +231,7 @@ public class DepositController implements Initializable, ChildController, Hibern setGraphic(copyIcon); copyIcon.setOnMouseClicked(e -> { Clipboard clipboard = Clipboard.getSystemClipboard(); - ClipboardContent content = new ClipboardContent(); + @NotNull ClipboardContent content = new ClipboardContent(); content.putString(item.addressStringProperty().get()); clipboard.setContent(content); }); @@ -249,6 +252,7 @@ public class DepositController implements Initializable, ChildController, Hibern confidenceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); confidenceColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { @@ -256,7 +260,7 @@ public class DepositController implements Initializable, ChildController, Hibern { @Override - public void updateItem(final DepositListItem item, boolean empty) + public void updateItem(@Nullable final DepositListItem item, boolean empty) { super.updateItem(item, empty); diff --git a/src/main/java/io/bitsquare/gui/funds/deposit/DepositListItem.java b/src/main/java/io/bitsquare/gui/funds/deposit/DepositListItem.java index ceefa4fc46..2c5a0f4085 100644 --- a/src/main/java/io/bitsquare/gui/funds/deposit/DepositListItem.java +++ b/src/main/java/io/bitsquare/gui/funds/deposit/DepositListItem.java @@ -3,10 +3,11 @@ package io.bitsquare.gui.funds.deposit; import io.bitsquare.btc.AddressEntry; import io.bitsquare.btc.WalletFacade; import io.bitsquare.gui.funds.withdrawal.WithdrawalListItem; +import org.jetbrains.annotations.NotNull; public class DepositListItem extends WithdrawalListItem { - public DepositListItem(AddressEntry addressEntry, WalletFacade walletFacade) + public DepositListItem(@NotNull AddressEntry addressEntry, @NotNull WalletFacade walletFacade) { super(addressEntry, walletFacade); } diff --git a/src/main/java/io/bitsquare/gui/funds/deposit/DepositView.fxml b/src/main/java/io/bitsquare/gui/funds/deposit/DepositView.fxml index d65799c30a..025b877c6b 100644 --- a/src/main/java/io/bitsquare/gui/funds/deposit/DepositView.fxml +++ b/src/main/java/io/bitsquare/gui/funds/deposit/DepositView.fxml @@ -14,7 +14,7 @@ - + diff --git a/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsController.java b/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsController.java index 48438dfd74..2699767fb3 100644 --- a/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsController.java +++ b/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsController.java @@ -17,6 +17,8 @@ import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.util.Callback; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,7 +27,7 @@ public class TransactionsController implements Initializable, ChildController, H private static final Logger log = LoggerFactory.getLogger(TransactionsController.class); private final WalletFacade walletFacade; - protected ObservableList transactionsListItems; + private ObservableList transactionsListItems; @FXML private TableView tableView; @@ -40,7 +42,7 @@ public class TransactionsController implements Initializable, ChildController, H /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public TransactionsController(WalletFacade walletFacade) + private TransactionsController(WalletFacade walletFacade) { this.walletFacade = walletFacade; } @@ -66,14 +68,14 @@ public class TransactionsController implements Initializable, ChildController, H /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { } @Override public void cleanup() { - for (TransactionsListItem transactionsListItem : transactionsListItems) + for (@NotNull TransactionsListItem transactionsListItem : transactionsListItems) { transactionsListItem.cleanup(); } @@ -120,6 +122,7 @@ public class TransactionsController implements Initializable, ChildController, H addressColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); addressColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { @@ -128,7 +131,7 @@ public class TransactionsController implements Initializable, ChildController, H Hyperlink hyperlink; @Override - public void updateItem(final TransactionsListItem item, boolean empty) + public void updateItem(@Nullable final TransactionsListItem item, boolean empty) { super.updateItem(item, empty); @@ -155,6 +158,7 @@ public class TransactionsController implements Initializable, ChildController, H confidenceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); confidenceColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { @@ -162,7 +166,7 @@ public class TransactionsController implements Initializable, ChildController, H { @Override - public void updateItem(final TransactionsListItem item, boolean empty) + public void updateItem(@Nullable final TransactionsListItem item, boolean empty) { super.updateItem(item, empty); diff --git a/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsListItem.java b/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsListItem.java index 9712dc6fc3..63826ce727 100644 --- a/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsListItem.java +++ b/src/main/java/io/bitsquare/gui/funds/transactions/TransactionsListItem.java @@ -13,6 +13,8 @@ import java.math.BigInteger; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.control.Tooltip; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,26 +24,27 @@ public class TransactionsListItem private final StringProperty date = new SimpleStringProperty(); private final StringProperty amount = new SimpleStringProperty(); private final StringProperty type = new SimpleStringProperty(); - private final Transaction transaction; + @NotNull private final WalletFacade walletFacade; + @NotNull private final ConfidenceProgressIndicator progressIndicator; + @NotNull private final Tooltip tooltip; private String addressString; private ConfidenceListener confidenceListener; - public TransactionsListItem(Transaction transaction, WalletFacade walletFacade) + public TransactionsListItem(@NotNull Transaction transaction, @NotNull WalletFacade walletFacade) { - this.transaction = transaction; this.walletFacade = walletFacade; BigInteger valueSentToMe = transaction.getValueSentToMe(walletFacade.getWallet()); BigInteger valueSentFromMe = transaction.getValueSentFromMe(walletFacade.getWallet()); - Address address = null; + @Nullable Address address = null; if (valueSentToMe.compareTo(BigInteger.ZERO) == 0) { amount.set("-" + BtcFormatter.satoshiToString(valueSentFromMe)); - for (TransactionOutput transactionOutput : transaction.getOutputs()) + for (@NotNull TransactionOutput transactionOutput : transaction.getOutputs()) { if (!transactionOutput.isMine(walletFacade.getWallet())) { @@ -64,7 +67,7 @@ public class TransactionsListItem amount.set(BtcFormatter.satoshiToString(valueSentToMe)); type.set("Received with"); - for (TransactionOutput transactionOutput : transaction.getOutputs()) + for (@NotNull TransactionOutput transactionOutput : transaction.getOutputs()) { if (transactionOutput.isMine(walletFacade.getWallet())) { @@ -85,7 +88,7 @@ public class TransactionsListItem amount.set(BtcFormatter.satoshiToString(valueSentToMe.subtract(valueSentFromMe))); boolean outgoing = false; - for (TransactionOutput transactionOutput : transaction.getOutputs()) + for (@NotNull TransactionOutput transactionOutput : transaction.getOutputs()) { if (!transactionOutput.isMine(walletFacade.getWallet())) { @@ -145,7 +148,7 @@ public class TransactionsListItem walletFacade.removeConfidenceListener(confidenceListener); } - private void updateConfidence(TransactionConfidence confidence) + private void updateConfidence(@Nullable TransactionConfidence confidence) { if (confidence != null) { @@ -175,21 +178,25 @@ public class TransactionsListItem } + @NotNull public ConfidenceProgressIndicator getProgressIndicator() { return progressIndicator; } + @NotNull public final StringProperty dateProperty() { return this.date; } + @NotNull public final StringProperty amountProperty() { return this.amount; } + @NotNull public final StringProperty typeProperty() { return this.type; diff --git a/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalController.java b/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalController.java index 6ee1de1433..1f2d16e65b 100644 --- a/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalController.java +++ b/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalController.java @@ -21,7 +21,6 @@ import java.util.stream.Collectors; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; @@ -30,6 +29,8 @@ import javafx.scene.input.ClipboardContent; import javafx.util.Callback; import org.controlsfx.control.action.Action; import org.controlsfx.dialog.Dialog; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,7 +40,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib private final WalletFacade walletFacade; - protected ObservableList addressList; + private ObservableList addressList; @FXML private TableView tableView; @@ -56,7 +57,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public WithdrawalController(WalletFacade walletFacade) + private WithdrawalController(WalletFacade walletFacade) { this.walletFacade = walletFacade; } @@ -82,7 +83,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib { BitSquareValidator.resetTextFields(withdrawFromTextField, withdrawToTextField, amountTextField, changeAddressTextField); - if (newValue.getBalance().compareTo(BigInteger.ZERO) > 0) + if (BigInteger.ZERO.compareTo(newValue.getBalance()) <= 0) { amountTextField.setText(BtcFormatter.satoshiToString(newValue.getBalance())); withdrawFromTextField.setText(newValue.getAddressEntry().getAddressString()); @@ -105,14 +106,14 @@ public class WithdrawalController implements Initializable, ChildController, Hib /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { } @Override public void cleanup() { - for (WithdrawalListItem anAddressList : addressList) + for (@NotNull WithdrawalListItem anAddressList : addressList) { anAddressList.cleanup(); } @@ -145,7 +146,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib /////////////////////////////////////////////////////////////////////////////////////////// @FXML - public void onWithdraw(ActionEvent actionEvent) + public void onWithdraw() { try { @@ -155,17 +156,17 @@ public class WithdrawalController implements Initializable, ChildController, Hib BigInteger amount = BtcFormatter.stringValueToSatoshis(amountTextField.getText()); if (BtcValidator.isMinSpendableAmount(amount)) { - FutureCallback callback = new FutureCallback() + @NotNull FutureCallback callback = new FutureCallback() { @Override - public void onSuccess(Transaction transaction) + public void onSuccess(@javax.annotation.Nullable Transaction transaction) { BitSquareValidator.resetTextFields(withdrawFromTextField, withdrawToTextField, amountTextField, changeAddressTextField); - log.info("onWithdraw onSuccess txid:" + transaction.getHashAsString()); + if (transaction != null) log.info("onWithdraw onSuccess txid:" + transaction.getHashAsString()); } @Override - public void onFailure(Throwable t) + public void onFailure(@NotNull Throwable t) { log.debug("onWithdraw onFailure"); } @@ -223,15 +224,17 @@ public class WithdrawalController implements Initializable, ChildController, Hib labelColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); labelColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { return new TableCell() { + @Nullable Hyperlink hyperlink; @Override - public void updateItem(final WithdrawalListItem item, boolean empty) + public void updateItem(@Nullable final WithdrawalListItem item, boolean empty) { super.updateItem(item, empty); @@ -241,7 +244,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib hyperlink.setId("id-link"); if (item.getAddressEntry().getTradeId() != null) { - Tooltip tooltip = new Tooltip(item.getAddressEntry().getTradeId()); + @NotNull Tooltip tooltip = new Tooltip(item.getAddressEntry().getTradeId()); Tooltip.install(hyperlink, tooltip); hyperlink.setOnAction(event -> log.info("Show trade details " + item.getAddressEntry().getTradeId())); @@ -264,13 +267,14 @@ public class WithdrawalController implements Initializable, ChildController, Hib balanceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); balanceColumn.setCellFactory(new Callback, TableCell>() { + @NotNull @Override public TableCell call(TableColumn column) { return new TableCell() { @Override - public void updateItem(final WithdrawalListItem item, boolean empty) + public void updateItem(@Nullable final WithdrawalListItem item, boolean empty) { super.updateItem(item, empty); setGraphic((item != null && !empty) ? item.getBalanceLabel() : null); @@ -285,6 +289,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib copyColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); copyColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { @@ -299,7 +304,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib } @Override - public void updateItem(final WithdrawalListItem item, boolean empty) + public void updateItem(@Nullable final WithdrawalListItem item, boolean empty) { super.updateItem(item, empty); @@ -308,7 +313,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib setGraphic(copyIcon); copyIcon.setOnMouseClicked(e -> { Clipboard clipboard = Clipboard.getSystemClipboard(); - ClipboardContent content = new ClipboardContent(); + @NotNull ClipboardContent content = new ClipboardContent(); content.putString(item.addressStringProperty().get()); clipboard.setContent(content); }); @@ -329,6 +334,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib confidenceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); confidenceColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { @@ -336,7 +342,7 @@ public class WithdrawalController implements Initializable, ChildController, Hib { @Override - public void updateItem(final WithdrawalListItem item, boolean empty) + public void updateItem(@Nullable final WithdrawalListItem item, boolean empty) { super.updateItem(item, empty); diff --git a/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalListItem.java b/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalListItem.java index cf6f0236de..be4c7ab049 100644 --- a/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalListItem.java +++ b/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalListItem.java @@ -13,20 +13,28 @@ import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class WithdrawalListItem { private final StringProperty addressString = new SimpleStringProperty(); private final BalanceListener balanceListener; + @NotNull private final Label balanceLabel; + @NotNull private final AddressEntry addressEntry; + @NotNull private final WalletFacade walletFacade; private final ConfidenceListener confidenceListener; + @NotNull private final ConfidenceProgressIndicator progressIndicator; + @NotNull private final Tooltip tooltip; + @Nullable private BigInteger balance; - public WithdrawalListItem(AddressEntry addressEntry, WalletFacade walletFacade) + public WithdrawalListItem(@NotNull AddressEntry addressEntry, @NotNull WalletFacade walletFacade) { this.addressEntry = addressEntry; this.walletFacade = walletFacade; @@ -73,7 +81,7 @@ public class WithdrawalListItem walletFacade.removeBalanceListener(balanceListener); } - private void updateBalance(BigInteger balance) + private void updateBalance(@Nullable BigInteger balance) { this.balance = balance; if (balance != null) @@ -82,7 +90,7 @@ public class WithdrawalListItem } } - private void updateConfidence(TransactionConfidence confidence) + private void updateConfidence(@Nullable TransactionConfidence confidence) { if (confidence != null) { @@ -111,6 +119,7 @@ public class WithdrawalListItem } } + @Nullable public final String getLabel() { switch (addressEntry.getAddressContext()) @@ -128,31 +137,36 @@ public class WithdrawalListItem return ""; } + @NotNull public final StringProperty addressStringProperty() { return this.addressString; } - public Address getAddress() + Address getAddress() { return addressEntry.getAddress(); } + @NotNull public AddressEntry getAddressEntry() { return addressEntry; } + @NotNull public ConfidenceProgressIndicator getProgressIndicator() { return progressIndicator; } + @NotNull public Label getBalanceLabel() { return balanceLabel; } + @Nullable public BigInteger getBalance() { return balance; diff --git a/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalView.fxml b/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalView.fxml index 8a311d2282..f8505d15a3 100644 --- a/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalView.fxml +++ b/src/main/java/io/bitsquare/gui/funds/withdrawal/WithdrawalView.fxml @@ -14,7 +14,7 @@ - + diff --git a/src/main/java/io/bitsquare/gui/home/HomeController.java b/src/main/java/io/bitsquare/gui/home/HomeController.java index 6f72e2af7c..33dea12d8a 100644 --- a/src/main/java/io/bitsquare/gui/home/HomeController.java +++ b/src/main/java/io/bitsquare/gui/home/HomeController.java @@ -10,7 +10,6 @@ import io.bitsquare.locale.Localisation; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; -import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; @@ -19,12 +18,13 @@ import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Modality; import javafx.stage.Stage; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class HomeController implements Initializable, ChildController, NavigationController { @FXML public Pane rootContainer; - private NavigationController navigationController; private ArbitratorRegistrationController arbitratorRegistrationController; @Override @@ -34,9 +34,8 @@ public class HomeController implements Initializable, ChildController, Navigatio } @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { - this.navigationController = navigationController; } @Override @@ -48,13 +47,14 @@ public class HomeController implements Initializable, ChildController, Navigatio // Interface implementation: NavigationController /////////////////////////////////////////////////////////////////////////////////////////// + @Nullable @Override - public ChildController navigateToView(NavigationItem navigationItem) + public ChildController navigateToView(@NotNull NavigationItem navigationItem) { if (arbitratorRegistrationController != null) arbitratorRegistrationController.cleanup(); - final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); + @NotNull final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); try { final Node view = loader.load(); @@ -62,7 +62,7 @@ public class HomeController implements Initializable, ChildController, Navigatio arbitratorRegistrationController.setNavigationController(this); final Stage rootStage = BitSquare.getStage(); - final Stage stage = new Stage(); + @NotNull final Stage stage = new Stage(); stage.setTitle("Arbitrator"); stage.setMinWidth(800); stage.setMinHeight(400); @@ -72,7 +72,7 @@ public class HomeController implements Initializable, ChildController, Navigatio stage.setY(rootStage.getY() + 50); stage.initModality(Modality.WINDOW_MODAL); stage.initOwner(rootStage); - Scene scene = new Scene((Parent) view, 800, 600); + @NotNull Scene scene = new Scene((Parent) view, 800, 600); stage.setScene(scene); stage.show(); @@ -85,13 +85,13 @@ public class HomeController implements Initializable, ChildController, Navigatio } @FXML - public void onArbitratorRegistration(ActionEvent actionEvent) + public void onArbitratorRegistration() { navigateToView(NavigationItem.ARBITRATOR_REGISTRATION); } @FXML - public void onArbitratorEdit(ActionEvent actionEvent) + public void onArbitratorEdit() { navigateToView(NavigationItem.ARBITRATOR_REGISTRATION); arbitratorRegistrationController.setEditMode(true); diff --git a/src/main/java/io/bitsquare/gui/market/MarketController.java b/src/main/java/io/bitsquare/gui/market/MarketController.java index 35e05c0366..c0733d4be8 100644 --- a/src/main/java/io/bitsquare/gui/market/MarketController.java +++ b/src/main/java/io/bitsquare/gui/market/MarketController.java @@ -15,12 +15,13 @@ import javafx.fxml.Initializable; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.Pane; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class MarketController implements Initializable, NavigationController, ChildController { - private ChildController childController; private boolean orderbookCreated; - private NavigationController navigationController; + @Nullable private OrderBookController orderBookController; @FXML @@ -42,8 +43,9 @@ public class MarketController implements Initializable, NavigationController, Ch // Interface implementation: NavigationController /////////////////////////////////////////////////////////////////////////////////////////// + @Nullable @Override - public ChildController navigateToView(NavigationItem navigationItem) + public ChildController navigateToView(@NotNull NavigationItem navigationItem) { if (navigationItem == NavigationItem.ORDER_BOOK && orderbookCreated) @@ -52,17 +54,17 @@ public class MarketController implements Initializable, NavigationController, Ch return null; } - final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); + @NotNull final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); try { Pane view = loader.load(); - childController = loader.getController(); + ChildController childController = loader.getController(); childController.setNavigationController(this); if (childController instanceof OrderBookController) orderBookController = (OrderBookController) childController; - Tab tab = new Tab("Orderbook"); + @NotNull Tab tab = new Tab("Orderbook"); tab.setContent(view); tabPane.getTabs().add(tab); @@ -88,10 +90,9 @@ public class MarketController implements Initializable, NavigationController, Ch /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { - this.navigationController = navigationController; } @Override diff --git a/src/main/java/io/bitsquare/gui/market/createOffer/CreateOfferController.java b/src/main/java/io/bitsquare/gui/market/createOffer/CreateOfferController.java index a6a1514863..1c71abe812 100644 --- a/src/main/java/io/bitsquare/gui/market/createOffer/CreateOfferController.java +++ b/src/main/java/io/bitsquare/gui/market/createOffer/CreateOfferController.java @@ -4,6 +4,7 @@ import com.google.bitcoin.core.InsufficientMoneyException; import com.google.bitcoin.core.Transaction; import com.google.common.util.concurrent.FutureCallback; import com.google.inject.Inject; +import io.bitsquare.bank.BankAccount; import io.bitsquare.btc.BtcFormatter; import io.bitsquare.btc.FeePolicy; import io.bitsquare.btc.WalletFacade; @@ -15,9 +16,7 @@ import io.bitsquare.gui.components.confidence.ConfidenceProgressIndicator; import io.bitsquare.gui.popups.Popups; import io.bitsquare.gui.util.BitSquareConverter; import io.bitsquare.gui.util.BitSquareFormatter; -import io.bitsquare.gui.util.ConfidenceDisplay; import io.bitsquare.locale.Localisation; -import io.bitsquare.msg.MessageFacade; import io.bitsquare.settings.Settings; import io.bitsquare.trade.Direction; import io.bitsquare.trade.Offer; @@ -30,7 +29,6 @@ import java.math.BigInteger; import java.net.URL; import java.util.Random; import java.util.ResourceBundle; -import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; @@ -38,21 +36,24 @@ import javafx.scene.control.Label; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CreateOfferController implements Initializable, ChildController, Hibernate { private static final Logger log = LoggerFactory.getLogger(CreateOfferController.class); + @NotNull private final Trading trading; + @NotNull private final WalletFacade walletFacade; - private final MessageFacade messageFacade; + @NotNull private final Settings settings; + @NotNull private final User user; private NavigationController navigationController; private Direction direction; private Offer offer; - private ConfidenceDisplay confidenceDisplay; @FXML private AnchorPane rootContainer; @@ -74,11 +75,10 @@ public class CreateOfferController implements Initializable, ChildController, Hi /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public CreateOfferController(Trading trading, WalletFacade walletFacade, MessageFacade messageFacade, Settings settings, User user) + private CreateOfferController(@NotNull Trading trading, @NotNull WalletFacade walletFacade, @NotNull Settings settings, @NotNull User user) { this.trading = trading; this.walletFacade = walletFacade; - this.messageFacade = messageFacade; this.settings = settings; this.user = user; } @@ -88,7 +88,7 @@ public class CreateOfferController implements Initializable, ChildController, Hi // Public methods /////////////////////////////////////////////////////////////////////////////////////////// - public void setOrderBookFilter(OrderBookFilter orderBookFilter) + public void setOrderBookFilter(@NotNull OrderBookFilter orderBookFilter) { direction = orderBookFilter.getDirection(); amountTextField.setText(BitSquareFormatter.formatPrice(orderBookFilter.getAmount())); @@ -119,9 +119,13 @@ public class CreateOfferController implements Initializable, ChildController, Hi @Override public void initialize(URL url, ResourceBundle rb) { - bankAccountTypeTextField.setText(Localisation.get(user.getCurrentBankAccount().getBankAccountTypeInfo().getType().toString())); - bankAccountCurrencyTextField.setText(user.getCurrentBankAccount().getCurrency().getCurrencyCode()); - bankAccountCountyTextField.setText(user.getCurrentBankAccount().getCountry().getName()); + BankAccount currentBankAccount = user.getCurrentBankAccount(); + if (currentBankAccount != null) + { + bankAccountTypeTextField.setText(Localisation.get(currentBankAccount.getBankAccountType().toString())); + bankAccountCurrencyTextField.setText(currentBankAccount.getCurrency().getCurrencyCode()); + bankAccountCountyTextField.setText(currentBankAccount.getCountry().getName()); + } acceptedCountriesTextField.setText(BitSquareFormatter.countryLocalesToString(settings.getAcceptedCountries())); acceptedLanguagesTextField.setText(BitSquareFormatter.languageLocalesToString(settings.getAcceptedLanguageLocales())); feeLabel.setText(BtcFormatter.satoshiToString(FeePolicy.CREATE_OFFER_FEE)); @@ -133,7 +137,7 @@ public class CreateOfferController implements Initializable, ChildController, Hi /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { this.navigationController = navigationController; } @@ -164,7 +168,7 @@ public class CreateOfferController implements Initializable, ChildController, Hi // UI Handlers /////////////////////////////////////////////////////////////////////////////////////////// - public void onPlaceOffer(ActionEvent actionEvent) + public void onPlaceOffer() { if (!inputValid()) { @@ -182,60 +186,68 @@ public class CreateOfferController implements Initializable, ChildController, Hi log.debug("create offer pubkey " + user.getMessagePubKeyAsHex()); - offer = new Offer(user.getMessagePubKeyAsHex(), - direction, - BitSquareConverter.stringToDouble2(priceTextField.getText()), - BtcFormatter.stringValueToSatoshis(amountTextField.getText()), - BtcFormatter.stringValueToSatoshis(minAmountTextField.getText()), - user.getCurrentBankAccount().getBankAccountTypeInfo().getType(), - user.getCurrentBankAccount().getCurrency(), - user.getCurrentBankAccount().getCountry(), - user.getCurrentBankAccount().getUid(), - arbitrator, - collateral, - settings.getAcceptedCountries(), - settings.getAcceptedLanguageLocales()); - - FutureCallback callback = new FutureCallback() + if (user.getCurrentBankAccount() != null) { - @Override - public void onSuccess(Transaction transaction) + offer = new Offer(user.getMessagePubKeyAsHex(), + direction, + BitSquareConverter.stringToDouble2(priceTextField.getText()), + BtcFormatter.stringValueToSatoshis(amountTextField.getText()), + BtcFormatter.stringValueToSatoshis(minAmountTextField.getText()), + user.getCurrentBankAccount().getBankAccountType(), + user.getCurrentBankAccount().getCurrency(), + user.getCurrentBankAccount().getCountry(), + user.getCurrentBankAccount().getUid(), + arbitrator, + collateral, + settings.getAcceptedCountries(), + settings.getAcceptedLanguageLocales()); + + + @NotNull FutureCallback callback = new FutureCallback() { - log.info("sendResult onSuccess:" + transaction.toString()); - offer.setOfferFeePaymentTxID(transaction.getHashAsString()); - setupSuccessScreen(transaction); - placeOfferTitle.setText("Transaction sent:"); - try + @Override + public void onSuccess(@javax.annotation.Nullable Transaction transaction) { - trading.addOffer(offer); - } catch (IOException e) - { - Popups.openErrorPopup("Error on adding offer", "Could not add offer to orderbook. " + e.getMessage()); + log.info("sendResult onSuccess:" + transaction); + if (transaction != null) + { + offer.setOfferFeePaymentTxID(transaction.getHashAsString()); + setupSuccessScreen(transaction); + + placeOfferTitle.setText("Transaction sent:"); + try + { + trading.addOffer(offer); + } catch (IOException e) + { + Popups.openErrorPopup("Error on adding offer", "Could not add offer to orderbook. " + e.getMessage()); + } + } } - } - @Override - public void onFailure(Throwable t) + @Override + public void onFailure(@NotNull Throwable t) + { + log.warn("sendResult onFailure:" + t); + Popups.openErrorPopup("Fee payment failed", "Fee payment failed. " + t); + placeOfferButton.setDisable(false); + } + }; + try { - log.warn("sendResult onFailure:" + t.toString()); - Popups.openErrorPopup("Fee payment failed", "Fee payment failed. " + t.toString()); - placeOfferButton.setDisable(false); + walletFacade.payCreateOfferFee(offer.getId(), callback); + placeOfferButton.setDisable(true); + } catch (InsufficientMoneyException e1) + { + Popups.openInsufficientMoneyPopup(); } - }; - - try - { - walletFacade.payCreateOfferFee(offer.getId(), callback); - placeOfferButton.setDisable(true); - } catch (InsufficientMoneyException e1) - { - Popups.openInsufficientMoneyPopup(); } } - public void onClose(ActionEvent actionEvent) + + public void onClose() { - TabPane tabPane = ((TabPane) (rootContainer.getParent().getParent())); + @NotNull TabPane tabPane = ((TabPane) (rootContainer.getParent().getParent())); tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedItem()); navigationController.navigateToView(NavigationItem.ORDER_BOOK); @@ -246,7 +258,7 @@ public class CreateOfferController implements Initializable, ChildController, Hi // Private methods /////////////////////////////////////////////////////////////////////////////////////////// - private void setupSuccessScreen(Transaction newTransaction) + private void setupSuccessScreen(@NotNull Transaction newTransaction) { placeOfferButton.setVisible(false); @@ -258,7 +270,7 @@ public class CreateOfferController implements Initializable, ChildController, Hi txTextField.setText(newTransaction.getHashAsString()); - confidenceDisplay = new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, newTransaction, progressIndicator); + // ConfidenceDisplay confidenceDisplay = new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, newTransaction, progressIndicator); } private void updateVolume() @@ -279,6 +291,7 @@ public class CreateOfferController implements Initializable, ChildController, Hi } //TODO + @SuppressWarnings("UnusedAssignment") private boolean inputValid() { double priceAsDouble = BitSquareConverter.stringToDouble2(priceTextField.getText()); diff --git a/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookController.java b/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookController.java index 3fd477896f..1e544e6db9 100644 --- a/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookController.java +++ b/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookController.java @@ -4,7 +4,7 @@ import com.google.bitcoin.core.InsufficientMoneyException; import com.google.bitcoin.core.Transaction; import com.google.common.util.concurrent.FutureCallback; import com.google.inject.Inject; -import io.bitsquare.bank.BankAccountTypeInfo; +import io.bitsquare.bank.BankAccountType; import io.bitsquare.btc.BtcFormatter; import io.bitsquare.btc.FeePolicy; import io.bitsquare.btc.WalletFacade; @@ -54,6 +54,8 @@ import javafx.util.Callback; import org.controlsfx.control.action.Action; import org.controlsfx.dialog.Dialog; import org.controlsfx.dialog.Dialogs; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -83,6 +85,7 @@ public class OrderBookController implements Initializable, ChildController public Button createOfferButton; private NavigationController navigationController; private SortedList offerList; + @Nullable private AnimationTimer pollingTimer; @FXML private TableColumn directionColumn, countryColumn, bankAccountTypeColumn; @@ -93,7 +96,7 @@ public class OrderBookController implements Initializable, ChildController /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public OrderBookController(OrderBook orderBook, OrderBookFilter orderBookFilter, User user, MessageFacade messageFacade, WalletFacade walletFacade, Settings settings, Storage storage) + private OrderBookController(OrderBook orderBook, OrderBookFilter orderBookFilter, User user, MessageFacade messageFacade, WalletFacade walletFacade, Settings settings, Storage storage) { this.orderBook = orderBook; this.orderBookFilter = orderBookFilter; @@ -153,7 +156,7 @@ public class OrderBookController implements Initializable, ChildController /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { this.navigationController = navigationController; } @@ -198,9 +201,9 @@ public class OrderBookController implements Initializable, ChildController private boolean areSettingsValid() { - return settings.getAcceptedLanguageLocales().size() > 0 && - settings.getAcceptedCountries().size() > 0 && - settings.getAcceptedArbitrators().size() > 0 && + return !settings.getAcceptedLanguageLocales().isEmpty() && + !settings.getAcceptedCountries().isEmpty() && + !settings.getAcceptedArbitrators().isEmpty() && user.getCurrentBankAccount() != null; } @@ -222,7 +225,7 @@ public class OrderBookController implements Initializable, ChildController Action response = Popups.openErrorPopup("Registration fee not confirmed yet", "The registration fee transaction has not been confirmed yet in the blockchain. Please wait until it has at least 1 confirmation."); if (response == Dialog.Actions.OK) { - MainController.getInstance().navigateToView(NavigationItem.FUNDS); + MainController.INSTANCE().navigateToView(NavigationItem.FUNDS); } } } @@ -231,7 +234,7 @@ public class OrderBookController implements Initializable, ChildController Action response = Popups.openErrorPopup("Missing registration fee", "You have not funded the full registration fee of " + BtcFormatter.satoshiToString(FeePolicy.ACCOUNT_REGISTRATION_FEE) + " BTC."); if (response == Dialog.Actions.OK) { - MainController.getInstance().navigateToView(NavigationItem.FUNDS); + MainController.INSTANCE().navigateToView(NavigationItem.FUNDS); } } } @@ -247,18 +250,18 @@ public class OrderBookController implements Initializable, ChildController if (selectedIndex >= 0) { - Dialogs.CommandLink settingsCommandLink = new Dialogs.CommandLink("Open settings", "You need to configure your settings before you can actively trade."); - Dialogs.CommandLink depositFeeCommandLink = new Dialogs.CommandLink("Deposit funds", "You need to pay the registration fee before you can actively trade. That is needed as prevention against fraud."); - Dialogs.CommandLink sendRegistrationCommandLink = new Dialogs.CommandLink("Publish registration", "When settings are configured and the fee deposit is done your registration transaction will be published to the Bitcoin \nnetwork."); - List commandLinks = Arrays.asList(settingsCommandLink, depositFeeCommandLink, sendRegistrationCommandLink); + @NotNull Dialogs.CommandLink settingsCommandLink = new Dialogs.CommandLink("Open settings", "You need to configure your settings before you can actively trade."); + @NotNull Dialogs.CommandLink depositFeeCommandLink = new Dialogs.CommandLink("Deposit funds", "You need to pay the registration fee before you can actively trade. That is needed as prevention against fraud."); + @NotNull Dialogs.CommandLink sendRegistrationCommandLink = new Dialogs.CommandLink("Publish registration", "When settings are configured and the fee deposit is done your registration transaction will be published to the Bitcoin \nnetwork."); + @NotNull List commandLinks = Arrays.asList(settingsCommandLink, depositFeeCommandLink, sendRegistrationCommandLink); Action registrationMissingAction = Popups.openRegistrationMissingPopup("Not registered yet", "Please follow these steps:", "You need to register before you can place an offer.", commandLinks, selectedIndex); if (registrationMissingAction == settingsCommandLink) { - MainController.getInstance().navigateToView(NavigationItem.SETTINGS); + MainController.INSTANCE().navigateToView(NavigationItem.SETTINGS); } else if (registrationMissingAction == depositFeeCommandLink) { - MainController.getInstance().navigateToView(NavigationItem.FUNDS); + MainController.INSTANCE().navigateToView(NavigationItem.FUNDS); } else if (registrationMissingAction == sendRegistrationCommandLink) { @@ -269,17 +272,17 @@ public class OrderBookController implements Initializable, ChildController private void payRegistrationFee() { - FutureCallback callback = new FutureCallback() + @NotNull FutureCallback callback = new FutureCallback() { @Override - public void onSuccess(Transaction transaction) + public void onSuccess(@javax.annotation.Nullable Transaction transaction) { log.debug("payRegistrationFee onSuccess"); - log.info("payRegistrationFee onSuccess txid:" + transaction.getHashAsString()); + if (transaction != null) log.info("payRegistrationFee onSuccess tx id:" + transaction.getHashAsString()); } @Override - public void onFailure(Throwable t) + public void onFailure(@NotNull Throwable t) { log.debug("payRegistrationFee onFailure"); } @@ -287,8 +290,9 @@ public class OrderBookController implements Initializable, ChildController try { walletFacade.payRegistrationFee(user.getStringifiedBankAccounts(), callback); - user.setAccountID(walletFacade.getRegistrationAddressInfo().toString()); - user.setMessagePubKeyAsHex(DSAKeyUtil.getHexStringFromPublicKey(messageFacade.getPubKey())); + if (walletFacade.getRegistrationAddressInfo() != null) + user.setAccountID(walletFacade.getRegistrationAddressInfo().toString()); + if (messageFacade != null && messageFacade.getPubKey() != null) user.setMessagePubKeyAsHex(DSAKeyUtil.getHexStringFromPublicKey(messageFacade.getPubKey())); storage.write(user.getClass().getName(), user); } catch (InsufficientMoneyException e1) @@ -305,14 +309,15 @@ public class OrderBookController implements Initializable, ChildController if (walletFacade.isUnusedTradeAddressBalanceAboveCreationFee()) { ChildController nextController = navigationController.navigateToView(NavigationItem.CREATE_OFFER); - ((CreateOfferController) nextController).setOrderBookFilter(orderBookFilter); + if (nextController != null) + ((CreateOfferController) nextController).setOrderBookFilter(orderBookFilter); } else { Action response = Popups.openErrorPopup("No funds for a trade", "You have to add some funds before you create a new offer."); if (response == Dialog.Actions.OK) { - MainController.getInstance().navigateToView(NavigationItem.FUNDS); + MainController.INSTANCE().navigateToView(NavigationItem.FUNDS); } } } @@ -322,18 +327,18 @@ public class OrderBookController implements Initializable, ChildController } } - private void takeOffer(Offer offer) + private void takeOffer(@NotNull Offer offer) { if (isRegistered()) { - String title = offer.getDirection() == Direction.BUY ? "Trade: Sell Bitcoin" : "Trade: Buy Bitcoin"; - TakerTradeController takerTradeController = (TakerTradeController) navigationController.navigateToView(NavigationItem.TAKER_TRADE); + @Nullable TakerTradeController takerTradeController = (TakerTradeController) navigationController.navigateToView(NavigationItem.TAKER_TRADE); BigInteger requestedAmount = offer.getAmount(); - if (!amount.getText().equals("")) + if (!"".equals(amount.getText())) requestedAmount = BtcFormatter.stringValueToSatoshis(amount.getText()); - takerTradeController.initWithData(offer, requestedAmount); + if (takerTradeController != null) + takerTradeController.initWithData(offer, requestedAmount); } else { @@ -341,7 +346,7 @@ public class OrderBookController implements Initializable, ChildController } } - private void removeOffer(Offer offer) + private void removeOffer(@NotNull Offer offer) { orderBook.removeOffer(offer); } @@ -354,19 +359,19 @@ public class OrderBookController implements Initializable, ChildController orderBookTable.sort(); if (orderBookTable.getItems() != null) - createOfferButton.setDefaultButton(orderBookTable.getItems().size() == 0); + createOfferButton.setDefaultButton(orderBookTable.getItems().isEmpty()); } private void setupPolling() { - - pollingTimer = Utilities.setInterval(1000, (AnimationTimer animationTimer) -> { + pollingTimer = Utilities.setInterval(1000, (animationTimer) -> { if (user.getCurrentBankAccount() != null) messageFacade.getDirtyFlag(user.getCurrentBankAccount().getCurrency()); else messageFacade.getDirtyFlag(CurrencyUtil.getDefaultCurrency()); return null; }); + messageFacade.getIsDirtyProperty().addListener((observableValue, oldValue, newValue) -> orderBook.loadOffers()); } @@ -380,6 +385,7 @@ public class OrderBookController implements Initializable, ChildController directionColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); directionColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn directionColumn) { @@ -394,7 +400,7 @@ public class OrderBookController implements Initializable, ChildController } @Override - public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) + public void updateItem(@Nullable final OrderBookListItem orderBookListItem, boolean empty) { super.updateItem(orderBookListItem, empty); @@ -402,7 +408,7 @@ public class OrderBookController implements Initializable, ChildController { String title; Image icon; - Offer offer = orderBookListItem.getOffer(); + @NotNull Offer offer = orderBookListItem.getOffer(); if (offer.getMessagePubKeyAsHex().equals(user.getMessagePubKeyAsHex())) { @@ -447,6 +453,7 @@ public class OrderBookController implements Initializable, ChildController countryColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); countryColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn directionColumn) { @@ -461,7 +468,7 @@ public class OrderBookController implements Initializable, ChildController } @Override - public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) + public void updateItem(@Nullable final OrderBookListItem orderBookListItem, boolean empty) { super.updateItem(orderBookListItem, empty); @@ -490,19 +497,20 @@ public class OrderBookController implements Initializable, ChildController bankAccountTypeColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); bankAccountTypeColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn directionColumn) { return new TableCell() { @Override - public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) + public void updateItem(@Nullable final OrderBookListItem orderBookListItem, boolean empty) { super.updateItem(orderBookListItem, empty); if (orderBookListItem != null) { - BankAccountTypeInfo.BankAccountType bankAccountType = orderBookListItem.getOffer().getBankAccountType(); + BankAccountType bankAccountType = orderBookListItem.getOffer().getBankAccountType(); setText(Localisation.get(bankAccountType.toString())); } else @@ -520,15 +528,15 @@ public class OrderBookController implements Initializable, ChildController // Utils /////////////////////////////////////////////////////////////////////////////////////////// - private double textInputToNumber(String oldValue, String newValue) + private double textInputToNumber(String oldValue, @NotNull String newValue) { //TODO use regex.... or custom textfield component double d = 0.0; - if (!newValue.equals("")) + if (!"".equals(newValue)) { try { - DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault()); + @NotNull DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault()); d = decimalFormat.parse(newValue).doubleValue(); } catch (ParseException e) { diff --git a/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookListItem.java b/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookListItem.java index 949e2ebbd9..6c5a613929 100644 --- a/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookListItem.java +++ b/src/main/java/io/bitsquare/gui/market/orderbook/OrderBookListItem.java @@ -5,17 +5,19 @@ import io.bitsquare.gui.util.BitSquareFormatter; import io.bitsquare.trade.Offer; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; +import org.jetbrains.annotations.NotNull; public class OrderBookListItem { - protected final StringProperty price = new SimpleStringProperty(); - protected final StringProperty amount = new SimpleStringProperty(); - protected final StringProperty volume = new SimpleStringProperty(); + private final StringProperty price = new SimpleStringProperty(); + private final StringProperty amount = new SimpleStringProperty(); + private final StringProperty volume = new SimpleStringProperty(); - protected final Offer offer; + @NotNull + private final Offer offer; - public OrderBookListItem(Offer offer) + public OrderBookListItem(@NotNull Offer offer) { this.offer = offer; this.price.set(BitSquareFormatter.formatPrice(offer.getPrice())); @@ -27,22 +29,26 @@ public class OrderBookListItem this.volume.set(BitSquareFormatter.formatVolumeWithMinVolume(offer.getVolume(), offer.getMinVolume())); } + @NotNull public Offer getOffer() { return offer; } // called form table columns + @NotNull public final StringProperty priceProperty() { return this.price; } + @NotNull public final StringProperty amountProperty() { return this.amount; } + @NotNull public final StringProperty volumeProperty() { return this.volume; diff --git a/src/main/java/io/bitsquare/gui/market/trade/TakerTradeController.java b/src/main/java/io/bitsquare/gui/market/trade/TakerTradeController.java index d4028f5608..b013cec4a7 100644 --- a/src/main/java/io/bitsquare/gui/market/trade/TakerTradeController.java +++ b/src/main/java/io/bitsquare/gui/market/trade/TakerTradeController.java @@ -2,7 +2,10 @@ package io.bitsquare.gui.market.trade; import com.google.bitcoin.core.Transaction; import com.google.inject.Inject; -import io.bitsquare.btc.*; +import io.bitsquare.btc.AddressEntry; +import io.bitsquare.btc.BtcFormatter; +import io.bitsquare.btc.FeePolicy; +import io.bitsquare.btc.WalletFacade; import io.bitsquare.gui.ChildController; import io.bitsquare.gui.NavigationController; import io.bitsquare.gui.NavigationItem; @@ -34,31 +37,32 @@ import javafx.scene.control.*; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("UnusedParameters") public class TakerTradeController implements Initializable, ChildController { private static final Logger log = LoggerFactory.getLogger(TakerTradeController.class); private final Trading trading; private final WalletFacade walletFacade; - private final BlockChainFacade blockChainFacade; private final MessageFacade messageFacade; private final List processStepItems = new ArrayList<>(); private Offer offer; private Trade trade; private BigInteger requestedAmount; - private boolean offererIsOnline; private int row; private NavigationController navigationController; private TextField amountTextField, totalToPayLabel, totalLabel, collateralTextField, isOnlineTextField; - private Label statusTextField, infoLabel; + private Label infoLabel; private Button nextButton; private ProgressBar progressBar; + @Nullable private AnimationTimer checkOnlineStatusTimer; private Pane isOnlineCheckerHolder; - private TakerPaymentProtocol takerPaymentProtocol; private Label headerLabel; @FXML @@ -74,11 +78,10 @@ public class TakerTradeController implements Initializable, ChildController /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public TakerTradeController(Trading trading, WalletFacade walletFacade, BlockChainFacade blockChainFacade, MessageFacade messageFacade) + private TakerTradeController(Trading trading, WalletFacade walletFacade, MessageFacade messageFacade) { this.trading = trading; this.walletFacade = walletFacade; - this.blockChainFacade = blockChainFacade; this.messageFacade = messageFacade; } @@ -87,7 +90,7 @@ public class TakerTradeController implements Initializable, ChildController // Public methods /////////////////////////////////////////////////////////////////////////////////////////// - public void initWithData(Offer offer, BigInteger requestedAmount) + public void initWithData(@NotNull Offer offer, @NotNull BigInteger requestedAmount) { this.offer = offer; this.requestedAmount = requestedAmount.compareTo(BigInteger.ZERO) > 0 ? requestedAmount : offer.getAmount(); @@ -120,7 +123,7 @@ public class TakerTradeController implements Initializable, ChildController /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { this.navigationController = navigationController; } @@ -152,14 +155,14 @@ public class TakerTradeController implements Initializable, ChildController row = -1; FormBuilder.addHeaderLabel(gridPane, "Take offer:", ++row); - amountTextField = FormBuilder.addTextField(gridPane, "Amount (BTC):", BtcFormatter.formatSatoshis(requestedAmount, false), ++row, true, true); + amountTextField = FormBuilder.addTextField(gridPane, "Amount (BTC):", BtcFormatter.satoshiToString(requestedAmount), ++row, true, true); amountTextField.textProperty().addListener(e -> { applyVolume(); applyCollateral(); totalToPayLabel.setText(getTotalToPayAsString()); }); - Label amountRangeLabel = new Label("(" + BtcFormatter.formatSatoshis(offer.getMinAmount(), false) + " - " + BtcFormatter.formatSatoshis(offer.getAmount(), false) + ")"); + @NotNull Label amountRangeLabel = new Label("(" + BtcFormatter.satoshiToString(offer.getMinAmount()) + " - " + BtcFormatter.satoshiToString(offer.getAmount()) + ")"); gridPane.add(amountRangeLabel, 2, row); FormBuilder.addTextField(gridPane, "Price (" + offer.getCurrency() + "/BTC):", BitSquareFormatter.formatPrice(offer.getPrice()), ++row); @@ -170,7 +173,7 @@ public class TakerTradeController implements Initializable, ChildController totalToPayLabel = FormBuilder.addTextField(gridPane, "Total to pay (BTC):", getTotalToPayAsString(), ++row); isOnlineTextField = FormBuilder.addTextField(gridPane, "Online status:", "Checking offerers online status...", ++row); - ConfidenceProgressIndicator isOnlineChecker = new ConfidenceProgressIndicator(); + @NotNull ConfidenceProgressIndicator isOnlineChecker = new ConfidenceProgressIndicator(); isOnlineChecker.setPrefSize(20, 20); isOnlineChecker.setLayoutY(3); isOnlineCheckerHolder = new Pane(); @@ -181,6 +184,7 @@ public class TakerTradeController implements Initializable, ChildController messageFacade.pingPeer(offer.getMessagePubKeyAsHex()); checkOnlineStatusTimer = Utilities.setTimeout(1000, (AnimationTimer animationTimer) -> { setIsOnlineStatus(true); + //noinspection ReturnOfNull return null; }); @@ -194,13 +198,14 @@ public class TakerTradeController implements Initializable, ChildController FormBuilder.addTextField(gridPane, "Bank account type:", offer.getBankAccountType().toString(), ++row); FormBuilder.addTextField(gridPane, "Country:", offer.getBankAccountCountry().getName(), ++row); FormBuilder.addTextField(gridPane, "Arbitrator:", offer.getArbitrator().getName(), ++row); - Label arbitratorLink = new Label(offer.getArbitrator().getWebUrl()); + @NotNull Label arbitratorLink = new Label(offer.getArbitrator().getWebUrl()); arbitratorLink.setId("label-url"); gridPane.add(arbitratorLink, 2, row); arbitratorLink.setOnMouseClicked(e -> { try { - Utilities.openURL(offer.getArbitrator().getWebUrl()); + if (offer.getArbitrator() != null && offer.getArbitrator().getWebUrl() != null) + Utilities.openURL(offer.getArbitrator().getWebUrl()); } catch (Exception e1) { log.warn(e1.toString()); @@ -221,9 +226,9 @@ public class TakerTradeController implements Initializable, ChildController // offerId = tradeId // we don't want to create the trade before the balance check - AddressEntry addressEntry = walletFacade.getAddressInfoByTradeID(offer.getId()); - log.debug("balance " + walletFacade.getBalanceForAddress(addressEntry.getAddress()).toString()); - if (getTotalToPay().compareTo(walletFacade.getBalanceForAddress(addressEntry.getAddress())) > 0) + @Nullable AddressEntry addressEntry = walletFacade.getAddressInfoByTradeID(offer.getId()); + // log.debug("balance " + walletFacade.getBalanceForAddress(addressEntry.getAddress()).toString()); + if (getTotalToPay().compareTo(walletFacade.getBalanceForAddress(addressEntry != null ? addressEntry.getAddress() : null)) > 0) { Popups.openErrorPopup("Insufficient money", "You don't have enough funds for that trade."); return; @@ -251,7 +256,7 @@ public class TakerTradeController implements Initializable, ChildController row = -1; FormBuilder.addHeaderLabel(gridPane, "Trade request inited", ++row, 0); - statusTextField = FormBuilder.addLabel(gridPane, "Current activity:", "Request confirmation from offerer to take that offer.", ++row); + Label statusTextField = FormBuilder.addLabel(gridPane, "Current activity:", "Request confirmation from offerer to take that offer.", ++row); GridPane.setColumnSpan(statusTextField, 2); FormBuilder.addLabel(gridPane, "Progress:", "", ++row); progressBar = new ProgressBar(); @@ -261,14 +266,14 @@ public class TakerTradeController implements Initializable, ChildController gridPane.add(progressBar, 1, row); FormBuilder.addLabel(gridPane, "Status:", "", ++row); - ConfidenceProgressIndicator progressIndicator = new ConfidenceProgressIndicator(); + @NotNull ConfidenceProgressIndicator progressIndicator = new ConfidenceProgressIndicator(); progressIndicator.setPrefSize(20, 20); progressIndicator.setLayoutY(2); - Pane progressIndicatorHolder = new Pane(); + @NotNull Pane progressIndicatorHolder = new Pane(); progressIndicatorHolder.getChildren().addAll(progressIndicator); gridPane.add(progressIndicatorHolder, 1, row); - takerPaymentProtocol = trading.addTakerPaymentProtocol(trade, new TakerPaymentProtocolListener() + TakerPaymentProtocol takerPaymentProtocol = trading.addTakerPaymentProtocol(trade, new TakerPaymentProtocolListener() { @Override public void onProgress(double progress) @@ -311,7 +316,7 @@ public class TakerTradeController implements Initializable, ChildController } @Override - public void onBankTransferInited(TradeMessage tradeMessage) + public void onBankTransferInited(@NotNull TradeMessage tradeMessage) { buildBankTransferInitedScreen(tradeMessage); } @@ -326,6 +331,7 @@ public class TakerTradeController implements Initializable, ChildController takerPaymentProtocol.takeOffer(); } + @SuppressWarnings("EmptyMethod") private void updateTx(Trade trade) { @@ -344,7 +350,7 @@ public class TakerTradeController implements Initializable, ChildController // confidenceDisplay = new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, transaction, progressIndicator); } - private void buildBankTransferInitedScreen(TradeMessage tradeMessage) + private void buildBankTransferInitedScreen(@NotNull TradeMessage tradeMessage) { processStepBar.next(); @@ -355,7 +361,7 @@ public class TakerTradeController implements Initializable, ChildController nextButton.setOnAction(e -> releaseBTC(tradeMessage)); } - private void releaseBTC(TradeMessage tradeMessage) + private void releaseBTC(@NotNull TradeMessage tradeMessage) { processStepBar.next(); trading.releaseBTC(trade.getId(), tradeMessage); @@ -379,9 +385,9 @@ public class TakerTradeController implements Initializable, ChildController else { //TODO - FormBuilder.addTextField(gridPane, "You got returned collateral (BTC):", BtcFormatter.formatSatoshis(getCollateralInSatoshis(), false), ++row); + FormBuilder.addTextField(gridPane, "You got returned collateral (BTC):", BtcFormatter.satoshiToString(getCollateralInSatoshis()), ++row); FormBuilder.addTextField(gridPane, "You have received (" + offer.getCurrency() + "):", BitSquareFormatter.formatVolume(getVolume()), ++row); - FormBuilder.addTextField(gridPane, "You have received (BTC):", BtcFormatter.formatSatoshis(offer.getAmount(), false), ++row); + FormBuilder.addTextField(gridPane, "You have received (BTC):", BtcFormatter.satoshiToString(offer.getAmount()), ++row); } gridPane.add(nextButton, 1, ++row); @@ -395,7 +401,7 @@ public class TakerTradeController implements Initializable, ChildController private void close() { - TabPane tabPane = ((TabPane) (rootContainer.getParent().getParent())); + @NotNull TabPane tabPane = ((TabPane) (rootContainer.getParent().getParent())); tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedItem()); navigationController.navigateToView(NavigationItem.ORDER_BOOK); @@ -421,7 +427,8 @@ public class TakerTradeController implements Initializable, ChildController checkOnlineStatusTimer = null; } - offererIsOnline = isOnline; + //noinspection UnnecessaryLocalVariable + boolean offererIsOnline = isOnline; isOnlineTextField.setText(offererIsOnline ? "Online" : "Offline"); gridPane.getChildren().remove(isOnlineCheckerHolder); @@ -443,11 +450,11 @@ public class TakerTradeController implements Initializable, ChildController { if (takerIsSelling()) { - return BtcFormatter.formatSatoshis(getTotalToPay(), false); + return BtcFormatter.satoshiToString(getTotalToPay()); } else { - return BtcFormatter.formatSatoshis(getTotalToPay(), false) + "\n" + + return BtcFormatter.satoshiToString(getTotalToPay()) + "\n" + BitSquareFormatter.formatVolume(getVolume(), offer.getCurrency()); } } @@ -466,7 +473,7 @@ public class TakerTradeController implements Initializable, ChildController private void applyCollateral() { - collateralTextField.setText(BtcFormatter.formatSatoshis(getCollateralInSatoshis(), false)); + collateralTextField.setText(BtcFormatter.satoshiToString(getCollateralInSatoshis())); } private BigInteger getCollateralInSatoshis() diff --git a/src/main/java/io/bitsquare/gui/msg/MsgController.java b/src/main/java/io/bitsquare/gui/msg/MsgController.java index af934a3460..4c221eff53 100644 --- a/src/main/java/io/bitsquare/gui/msg/MsgController.java +++ b/src/main/java/io/bitsquare/gui/msg/MsgController.java @@ -6,6 +6,7 @@ import io.bitsquare.gui.NavigationController; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,7 +20,7 @@ public class MsgController implements Initializable, ChildController /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public MsgController() + private MsgController() { } @@ -39,7 +40,7 @@ public class MsgController implements Initializable, ChildController /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { } diff --git a/src/main/java/io/bitsquare/gui/orders/OrdersController.java b/src/main/java/io/bitsquare/gui/orders/OrdersController.java index f2a63c134c..45e3a96804 100644 --- a/src/main/java/io/bitsquare/gui/orders/OrdersController.java +++ b/src/main/java/io/bitsquare/gui/orders/OrdersController.java @@ -10,6 +10,7 @@ import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,7 +28,7 @@ public class OrdersController implements Initializable, ChildController, Navigat /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public OrdersController(Storage storage) + private OrdersController(Storage storage) { this.storage = storage; } @@ -49,7 +50,7 @@ public class OrdersController implements Initializable, ChildController, Navigat /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { } @@ -64,7 +65,7 @@ public class OrdersController implements Initializable, ChildController, Navigat /////////////////////////////////////////////////////////////////////////////////////////// @Override - public ChildController navigateToView(NavigationItem navigationItem) + public ChildController navigateToView(@NotNull NavigationItem navigationItem) { return tabPane.navigateToView(navigationItem.getFxmlUrl()); } diff --git a/src/main/java/io/bitsquare/gui/orders/closed/ClosedTradeController.java b/src/main/java/io/bitsquare/gui/orders/closed/ClosedTradeController.java index 0b2ae9a97c..ad0c91b2fd 100644 --- a/src/main/java/io/bitsquare/gui/orders/closed/ClosedTradeController.java +++ b/src/main/java/io/bitsquare/gui/orders/closed/ClosedTradeController.java @@ -7,6 +7,7 @@ import io.bitsquare.gui.NavigationController; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,7 +21,7 @@ public class ClosedTradeController implements Initializable, ChildController, Hi /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public ClosedTradeController() + private ClosedTradeController() { } @@ -40,7 +41,7 @@ public class ClosedTradeController implements Initializable, ChildController, Hi /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { log.debug("setNavigationController" + this); } diff --git a/src/main/java/io/bitsquare/gui/orders/offer/OfferController.java b/src/main/java/io/bitsquare/gui/orders/offer/OfferController.java index 39989a85e0..400272439c 100644 --- a/src/main/java/io/bitsquare/gui/orders/offer/OfferController.java +++ b/src/main/java/io/bitsquare/gui/orders/offer/OfferController.java @@ -7,6 +7,7 @@ import io.bitsquare.gui.NavigationController; import io.bitsquare.gui.util.Icons; import io.bitsquare.trade.Offer; import io.bitsquare.trade.Trading; +import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; @@ -21,14 +22,17 @@ import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.util.Callback; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("EmptyMethod") public class OfferController implements Initializable, ChildController, Hibernate { private static final Logger log = LoggerFactory.getLogger(OfferController.class); private final Trading trading; - protected ObservableList offerListItems; + private ObservableList offerListItems; @FXML private TableColumn offerIdColumn, dateColumn, amountColumn, priceColumn, volumeColumn, removeColumn; @FXML @@ -40,7 +44,7 @@ public class OfferController implements Initializable, ChildController, Hibernat /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public OfferController(Trading trading) + private OfferController(Trading trading) { this.trading = trading; } @@ -64,7 +68,7 @@ public class OfferController implements Initializable, ChildController, Hibernat // Interface implementation: ChildController /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { log.debug("setNavigationController" + this); } @@ -91,7 +95,7 @@ public class OfferController implements Initializable, ChildController, Hibernat { offerListItems = FXCollections.observableArrayList(); Map offerMap = trading.getOffers(); - List offerList = new ArrayList<>(offerMap.values()); + @NotNull List offerList = new ArrayList<>(offerMap.values()); offerListItems.addAll(offerList.stream().map(OfferListItem::new).collect(Collectors.toList())); offerTable.setItems(offerListItems); } @@ -107,12 +111,19 @@ public class OfferController implements Initializable, ChildController, Hibernat /////////////////////////////////////////////////////////////////////////////////////////// - private void removeOffer(OfferListItem offerListItem) + private void removeOffer(@NotNull OfferListItem offerListItem) { - trading.removeOffer(offerListItem.getOffer()); + try + { + trading.removeOffer(offerListItem.getOffer()); + } catch (IOException e) + { + e.printStackTrace(); + } offerListItems.remove(offerListItem); } + @SuppressWarnings("UnusedParameters") private void openOfferDetails(OfferListItem offerListItem) { @@ -127,6 +138,7 @@ public class OfferController implements Initializable, ChildController, Hibernat offerIdColumn.setCellValueFactory((offerListItem) -> new ReadOnlyObjectWrapper(offerListItem.getValue())); offerIdColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn column) { @@ -135,7 +147,7 @@ public class OfferController implements Initializable, ChildController, Hibernat Hyperlink hyperlink; @Override - public void updateItem(final OfferListItem item, boolean empty) + public void updateItem(@Nullable final OfferListItem item, boolean empty) { super.updateItem(item, empty); @@ -143,12 +155,9 @@ public class OfferController implements Initializable, ChildController, Hibernat { hyperlink = new Hyperlink(item.getOfferId()); //hyperlink.getStyleClass().setAll("aaa"); - if (item != null && !empty) - { - Tooltip tooltip = new Tooltip(item.getOfferId()); - Tooltip.install(hyperlink, tooltip); - hyperlink.setOnAction(event -> openOfferDetails(item)); - } + @NotNull Tooltip tooltip = new Tooltip(item.getOfferId()); + Tooltip.install(hyperlink, tooltip); + hyperlink.setOnAction(event -> openOfferDetails(item)); setGraphic(hyperlink); } else @@ -167,6 +176,7 @@ public class OfferController implements Initializable, ChildController, Hibernat removeColumn.setCellValueFactory((offerListItem) -> new ReadOnlyObjectWrapper(offerListItem.getValue())); removeColumn.setCellFactory(new Callback, TableCell>() { + @Nullable @Override public TableCell call(TableColumn directionColumn) { @@ -182,7 +192,7 @@ public class OfferController implements Initializable, ChildController, Hibernat } @Override - public void updateItem(final OfferListItem offerListItem, boolean empty) + public void updateItem(@Nullable final OfferListItem offerListItem, boolean empty) { super.updateItem(offerListItem, empty); diff --git a/src/main/java/io/bitsquare/gui/orders/offer/OfferListItem.java b/src/main/java/io/bitsquare/gui/orders/offer/OfferListItem.java index 7b7e40f425..e40b895e30 100644 --- a/src/main/java/io/bitsquare/gui/orders/offer/OfferListItem.java +++ b/src/main/java/io/bitsquare/gui/orders/offer/OfferListItem.java @@ -5,17 +5,19 @@ import io.bitsquare.gui.util.BitSquareFormatter; import io.bitsquare.trade.Offer; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; +import org.jetbrains.annotations.NotNull; public class OfferListItem { - protected final StringProperty price = new SimpleStringProperty(); - protected final StringProperty amount = new SimpleStringProperty(); - protected final StringProperty date = new SimpleStringProperty(); - protected final StringProperty volume = new SimpleStringProperty(); - protected final Offer offer; + private final StringProperty price = new SimpleStringProperty(); + private final StringProperty amount = new SimpleStringProperty(); + private final StringProperty date = new SimpleStringProperty(); + private final StringProperty volume = new SimpleStringProperty(); + @NotNull + private final Offer offer; private final String offerId; - public OfferListItem(Offer offer) + public OfferListItem(@NotNull Offer offer) { this.offer = offer; @@ -30,6 +32,7 @@ public class OfferListItem this.offerId = offer.getId(); } + @NotNull public Offer getOffer() { return offer; @@ -37,21 +40,25 @@ public class OfferListItem // called form table columns + @NotNull public final StringProperty dateProperty() { return this.date; } + @NotNull public final StringProperty priceProperty() { return this.price; } + @NotNull public final StringProperty amountProperty() { return this.amount; } + @NotNull public final StringProperty volumeProperty() { return this.volume; diff --git a/src/main/java/io/bitsquare/gui/orders/pending/PendingTradeController.java b/src/main/java/io/bitsquare/gui/orders/pending/PendingTradeController.java index a2aa5d5cbb..1a91dfe89d 100644 --- a/src/main/java/io/bitsquare/gui/orders/pending/PendingTradeController.java +++ b/src/main/java/io/bitsquare/gui/orders/pending/PendingTradeController.java @@ -7,6 +7,7 @@ import io.bitsquare.gui.NavigationController; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,7 +21,7 @@ public class PendingTradeController implements Initializable, ChildController, H /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public PendingTradeController() + private PendingTradeController() { } @@ -40,7 +41,7 @@ public class PendingTradeController implements Initializable, ChildController, H /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { log.debug("setNavigationController" + this); } diff --git a/src/main/java/io/bitsquare/gui/orders/pending/TradesTableItem.java b/src/main/java/io/bitsquare/gui/orders/pending/TradesTableItem.java index fea08b9e05..6c4fadf0d3 100644 --- a/src/main/java/io/bitsquare/gui/orders/pending/TradesTableItem.java +++ b/src/main/java/io/bitsquare/gui/orders/pending/TradesTableItem.java @@ -2,22 +2,25 @@ package io.bitsquare.gui.orders.pending; import io.bitsquare.gui.market.orderbook.OrderBookListItem; import io.bitsquare.trade.Trade; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class TradesTableItem extends OrderBookListItem +class TradesTableItem extends OrderBookListItem { private static final Logger log = LoggerFactory.getLogger(TradesTableItem.class); + @NotNull private final Trade trade; - public TradesTableItem(Trade trade) + private TradesTableItem(@NotNull Trade trade) { super(trade.getOffer()); this.trade = trade; } + @NotNull public Trade getTrade() { return trade; diff --git a/src/main/java/io/bitsquare/gui/popups/Popups.java b/src/main/java/io/bitsquare/gui/popups/Popups.java index 389f55c288..04caec53a1 100644 --- a/src/main/java/io/bitsquare/gui/popups/Popups.java +++ b/src/main/java/io/bitsquare/gui/popups/Popups.java @@ -9,7 +9,9 @@ import javafx.application.Platform; import org.controlsfx.control.action.Action; import org.controlsfx.dialog.Dialog; import org.controlsfx.dialog.Dialogs; +import org.jetbrains.annotations.NotNull; +@SuppressWarnings({"SameParameterValue", "WeakerAccess"}) public class Popups { @@ -37,7 +39,7 @@ public class Popups public static Action openConfirmPopup(String title, String message, String masthead) { - List actions = new ArrayList<>(); + @NotNull List actions = new ArrayList<>(); actions.add(Dialog.Actions.OK); actions.add(Dialog.Actions.CANCEL); return Dialogs.create() @@ -113,12 +115,13 @@ public class Popups } // Support handling of uncaught exception from any thread (also non gui thread) - public static void handleUncaughtExceptions(Throwable throwable) + @SuppressWarnings("ThrowableResultOfMethodCallIgnored") + public static void handleUncaughtExceptions(@NotNull Throwable throwable) { // while dev throwable.printStackTrace(); - Runnable runnable = () -> + @NotNull Runnable runnable = () -> { if (Throwables.getRootCause(throwable) instanceof BlockStoreException) { @@ -148,7 +151,7 @@ public class Popups openWarningPopup("Not enough money available", "There is not enough money available. Please pay in first to your wallet.", null); } - public static Action openRegistrationMissingPopup(String title, String message, String masthead, List commandLinks, int selectedIndex) + public static Action openRegistrationMissingPopup(String title, String message, String masthead, @NotNull List commandLinks, int selectedIndex) { return Dialogs.create() .owner(BitSquare.getStage()) diff --git a/src/main/java/io/bitsquare/gui/settings/SettingsController.java b/src/main/java/io/bitsquare/gui/settings/SettingsController.java index 38b160176c..a21e48e294 100644 --- a/src/main/java/io/bitsquare/gui/settings/SettingsController.java +++ b/src/main/java/io/bitsquare/gui/settings/SettingsController.java @@ -5,8 +5,7 @@ import com.google.bitcoin.core.Utils; import com.google.inject.Inject; import io.bitsquare.BitSquare; import io.bitsquare.bank.BankAccount; -import io.bitsquare.bank.BankAccountTypeInfo; -import io.bitsquare.btc.WalletFacade; +import io.bitsquare.bank.BankAccountType; import io.bitsquare.di.GuiceFXMLLoader; import io.bitsquare.gui.ChildController; import io.bitsquare.gui.NavigationController; @@ -26,7 +25,6 @@ import java.net.URL; import java.util.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; @@ -40,22 +38,23 @@ import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.StringConverter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; // TODO separate in 2 view/controllers public class SettingsController implements Initializable, ChildController, NavigationController { private final User user; + @NotNull private final Settings settings; + @NotNull private final Storage storage; - private final WalletFacade walletFacade; private final MessageFacade messageFacade; private final ObservableList languageList; private final ObservableList countryList; - private NavigationController navigationController; private ChildController childController; private List regionList; private ObservableList arbitratorList; - private Region selectedRegion, selectedBankAccountRegion; @FXML private ListView languagesListView; @@ -76,7 +75,7 @@ public class SettingsController implements Initializable, ChildController, Navig @FXML private ComboBox bankAccountComboBox; @FXML - private ComboBox bankAccountTypesComboBox; + private ComboBox bankAccountTypesComboBox; @FXML private ComboBox bankAccountCurrencyComboBox; @@ -86,12 +85,11 @@ public class SettingsController implements Initializable, ChildController, Navig /////////////////////////////////////////////////////////////////////////////////////////// @Inject - public SettingsController(User user, Settings settings, Storage storage, WalletFacade walletFacade, MessageFacade messageFacade) + public SettingsController(User user, @NotNull Settings settings, @NotNull Storage storage, MessageFacade messageFacade) { this.user = user; this.settings = settings; this.storage = storage; - this.walletFacade = walletFacade; this.messageFacade = messageFacade; Settings savedSettings = (Settings) storage.read(settings.getClass().getName()); @@ -118,7 +116,7 @@ public class SettingsController implements Initializable, ChildController, Navig // Public Methods /////////////////////////////////////////////////////////////////////////////////////////// - public void updateArbitrators() + void updateArbitrators() { arbitratorList = FXCollections.observableArrayList(settings.getAcceptedArbitrators()); initArbitrators(); @@ -137,21 +135,22 @@ public class SettingsController implements Initializable, ChildController, Navig addMockArbitrator(); } + @SuppressWarnings("ConstantConditions") private void addMockArbitrator() { - if (settings.getAcceptedArbitrators() == null || settings.getAcceptedArbitrators().size() == 0) + if (settings.getAcceptedArbitrators().isEmpty()) { String pubKeyAsHex = Utils.bytesToHexString(new ECKey().getPubKey()); String messagePubKeyAsHex = DSAKeyUtil.getHexStringFromPublicKey(messageFacade.getPubKey()); - List languages = new ArrayList<>(); + @NotNull List languages = new ArrayList<>(); languages.add(LanguageUtil.getDefaultLanguageLocale()); - List arbitrationMethods = new ArrayList<>(); + @NotNull List arbitrationMethods = new ArrayList<>(); arbitrationMethods.add(Arbitrator.METHOD.TLS_NOTARY); - List idVerifications = new ArrayList<>(); + @NotNull List idVerifications = new ArrayList<>(); idVerifications.add(Arbitrator.ID_VERIFICATION.PASSPORT); idVerifications.add(Arbitrator.ID_VERIFICATION.GOV_ID); - Arbitrator arbitrator = new Arbitrator(pubKeyAsHex, + @NotNull Arbitrator arbitrator = new Arbitrator(pubKeyAsHex, messagePubKeyAsHex, "Manfred Karrer", Arbitrator.ID_TYPE.REAL_LIFE_ID, @@ -188,9 +187,9 @@ public class SettingsController implements Initializable, ChildController, Navig /////////////////////////////////////////////////////////////////////////////////////////// @Override - public void setNavigationController(NavigationController navigationController) + public void setNavigationController(@NotNull NavigationController navigationController) { - this.navigationController = navigationController; + } @Override @@ -204,14 +203,15 @@ public class SettingsController implements Initializable, ChildController, Navig // Interface implementation: NavigationController /////////////////////////////////////////////////////////////////////////////////////////// + @Nullable @Override - public ChildController navigateToView(NavigationItem navigationItem) + public ChildController navigateToView(@NotNull NavigationItem navigationItem) { if (childController != null) childController.cleanup(); - final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); + @NotNull final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(navigationItem.getFxmlUrl()), Localisation.getResourceBundle()); try { final Node view = loader.load(); @@ -219,7 +219,7 @@ public class SettingsController implements Initializable, ChildController, Navig childController.setNavigationController(this); final Stage rootStage = BitSquare.getStage(); - final Stage stage = new Stage(); + @NotNull final Stage stage = new Stage(); stage.setTitle("Arbitrator selection"); stage.setMinWidth(800); stage.setMinHeight(500); @@ -229,7 +229,7 @@ public class SettingsController implements Initializable, ChildController, Navig stage.setY(rootStage.getY() + 50); stage.initModality(Modality.WINDOW_MODAL); stage.initOwner(rootStage); - Scene scene = new Scene((Parent) view, 800, 600); + @NotNull Scene scene = new Scene((Parent) view, 800, 600); stage.setScene(scene); stage.setOnHidden(windowEvent -> { if (navigationItem == NavigationItem.ARBITRATOR_OVERVIEW) @@ -253,29 +253,29 @@ public class SettingsController implements Initializable, ChildController, Navig // General Settings @FXML - public void onAddLanguage(ActionEvent actionEvent) + public void onAddLanguage() { addLanguage(languageComboBox.getSelectionModel().getSelectedItem()); languageComboBox.getSelectionModel().clearSelection(); } @FXML - public void onSelectRegion(ActionEvent actionEvent) + public void onSelectRegion() { countryComboBox.setVisible(true); - selectedRegion = regionComboBox.getSelectionModel().getSelectedItem(); + Region selectedRegion = regionComboBox.getSelectionModel().getSelectedItem(); countryComboBox.setItems(FXCollections.observableArrayList(CountryUtil.getAllCountriesFor(selectedRegion))); } @FXML - public void onAddCountry(ActionEvent actionEvent) + public void onAddCountry() { addCountry(countryComboBox.getSelectionModel().getSelectedItem()); countryComboBox.getSelectionModel().clearSelection(); } @FXML - public void onAddArbitrator(ActionEvent actionEvent) + public void onAddArbitrator() { navigateToView(NavigationItem.ARBITRATOR_OVERVIEW); } @@ -283,7 +283,7 @@ public class SettingsController implements Initializable, ChildController, Navig // Bank Account Settings @FXML - public void selectBankAccount(ActionEvent actionEvent) + public void selectBankAccount() { BankAccount bankAccount = bankAccountComboBox.getSelectionModel().getSelectedItem(); if (bankAccount != null && bankAccount != user.getCurrentBankAccount()) @@ -295,41 +295,41 @@ public class SettingsController implements Initializable, ChildController, Navig } @FXML - public void selectBankAccountType(ActionEvent actionEvent) + public void selectBankAccountType() { - BankAccountTypeInfo bankAccountTypeInfo = bankAccountTypesComboBox.getSelectionModel().getSelectedItem(); - if (bankAccountTypeInfo != null) + BankAccountType bankAccountType = bankAccountTypesComboBox.getSelectionModel().getSelectedItem(); + if (bankAccountType != null) { bankAccountTitleTextField.setText(""); bankAccountPrimaryIDTextField.setText(""); - bankAccountPrimaryIDTextField.setPromptText(bankAccountTypeInfo.getPrimaryIDName()); + bankAccountPrimaryIDTextField.setPromptText(bankAccountType.getPrimaryId()); bankAccountSecondaryIDTextField.setText(""); - bankAccountSecondaryIDTextField.setPromptText(bankAccountTypeInfo.getSecondaryIDName()); + bankAccountSecondaryIDTextField.setPromptText(bankAccountType.getSecondaryId()); } } @FXML - public void onSelectBankAccountRegion(ActionEvent actionEvent) + public void onSelectBankAccountRegion() { bankAccountCountryComboBox.setVisible(true); - selectedBankAccountRegion = bankAccountRegionComboBox.getSelectionModel().getSelectedItem(); + Region selectedBankAccountRegion = bankAccountRegionComboBox.getSelectionModel().getSelectedItem(); bankAccountCountryComboBox.setItems(FXCollections.observableArrayList(CountryUtil.getAllCountriesFor(selectedBankAccountRegion))); } @FXML - public void onAddBankAccount(ActionEvent actionEvent) + public void onAddBankAccount() { resetBankAccountInput(); } @FXML - public void onRemoveBankAccount(ActionEvent actionEvent) + public void onRemoveBankAccount() { removeBankAccount(); } @FXML - public void onSaveBankAccount(ActionEvent actionEvent) + void onSaveBankAccount() { saveBankAccount(); @@ -354,6 +354,7 @@ public class SettingsController implements Initializable, ChildController, Navig { languagesListView.setCellFactory(new Callback, ListCell>() { + @Nullable @Override public ListCell call(ListView list) { @@ -378,7 +379,7 @@ public class SettingsController implements Initializable, ChildController, Navig } @Override - public void updateItem(final Locale item, boolean empty) + public void updateItem(@Nullable final Locale item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) @@ -404,11 +405,12 @@ public class SettingsController implements Initializable, ChildController, Navig languageComboBox.setConverter(new StringConverter() { @Override - public String toString(Locale locale) + public String toString(@NotNull Locale locale) { return locale.getDisplayLanguage(); } + @Nullable @Override public Locale fromString(String s) { @@ -423,11 +425,12 @@ public class SettingsController implements Initializable, ChildController, Navig regionComboBox.setConverter(new StringConverter() { @Override - public String toString(Region region) + public String toString(@NotNull Region region) { return region.getName(); } + @Nullable @Override public Region fromString(String s) { @@ -437,6 +440,7 @@ public class SettingsController implements Initializable, ChildController, Navig countriesListView.setCellFactory(new Callback, ListCell>() { + @Nullable @Override public ListCell call(ListView list) { @@ -462,7 +466,7 @@ public class SettingsController implements Initializable, ChildController, Navig @Override - public void updateItem(final Country item, boolean empty) + public void updateItem(@Nullable final Country item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) @@ -486,12 +490,14 @@ public class SettingsController implements Initializable, ChildController, Navig countryComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(Country country) + public String toString(@NotNull Country country) { return country.getName(); } + @Nullable @Override public Country fromString(String s) { @@ -505,6 +511,7 @@ public class SettingsController implements Initializable, ChildController, Navig { arbitratorsListView.setCellFactory(new Callback, ListCell>() { + @Nullable @Override public ListCell call(ListView list) { @@ -530,7 +537,7 @@ public class SettingsController implements Initializable, ChildController, Navig @Override - public void updateItem(final Arbitrator item, boolean empty) + public void updateItem(@Nullable final Arbitrator item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) @@ -553,47 +560,56 @@ public class SettingsController implements Initializable, ChildController, Navig arbitratorsListView.setItems(arbitratorList); } - private void addLanguage(Locale item) + private void addLanguage(@Nullable Locale item) { if (!languageList.contains(item) && item != null) { languageList.add(item); settings.addAcceptedLanguageLocale(item); - storage.write(settings.getClass().getName(), settings); + } } - private void removeLanguage(Locale item) + private void removeLanguage(@NotNull Locale item) { languageList.remove(item); settings.removeAcceptedLanguageLocale(item); - storage.write(settings.getClass().getName(), settings); + saveSettings(); } - private void addCountry(Country item) + private void addCountry(@Nullable Country item) { if (!countryList.contains(item) && item != null) { countryList.add(item); settings.addAcceptedCountry(item); - storage.write(settings.getClass().getName(), settings); + saveSettings(); } } - private void removeCountry(Country item) + private void removeCountry(@NotNull Country item) { countryList.remove(item); settings.removeAcceptedCountry(item); - storage.write(settings.getClass().getName(), settings); + saveSettings(); } - private void removeArbitrator(Arbitrator item) + private void removeArbitrator(@NotNull Arbitrator item) { arbitratorList.remove(item); settings.removeAcceptedArbitrator(item); + saveSettings(); + } + + private void saveSettings() + { storage.write(settings.getClass().getName(), settings); } + private void saveUser() + { + storage.write(user.getClass().getName(), user); + } /////////////////////////////////////////////////////////////////////////////////////////// // Bank Account Settings @@ -612,9 +628,9 @@ public class SettingsController implements Initializable, ChildController, Navig bankAccountTitleTextField.setText(currentBankAccount.getAccountTitle()); bankAccountHolderNameTextField.setText(currentBankAccount.getAccountHolderName()); bankAccountPrimaryIDTextField.setText(currentBankAccount.getAccountPrimaryID()); - bankAccountPrimaryIDTextField.setPromptText(currentBankAccount.getBankAccountTypeInfo().getPrimaryIDName()); + bankAccountPrimaryIDTextField.setPromptText(currentBankAccount.getBankAccountType().getPrimaryId()); bankAccountSecondaryIDTextField.setText(currentBankAccount.getAccountSecondaryID()); - bankAccountSecondaryIDTextField.setPromptText(currentBankAccount.getBankAccountTypeInfo().getSecondaryIDName()); + bankAccountSecondaryIDTextField.setPromptText(currentBankAccount.getBankAccountType().getSecondaryId()); } else { @@ -631,7 +647,7 @@ public class SettingsController implements Initializable, ChildController, Navig bankAccountPrimaryIDTextField.setText("dummy"); bankAccountSecondaryIDTextField.setText("dummy"); if (user.getCurrentBankAccount() == null) - onSaveBankAccount(null); + onSaveBankAccount(); } private void resetBankAccountInput() @@ -649,19 +665,26 @@ public class SettingsController implements Initializable, ChildController, Navig private void initBankAccountComboBox() { - if (user.getBankAccounts().size() > 0) + if (user.getBankAccounts().isEmpty()) + { + bankAccountComboBox.setPromptText("No bank account available"); + bankAccountComboBox.setDisable(true); + } + else { bankAccountComboBox.setPromptText("Select bank account"); bankAccountComboBox.setDisable(false); bankAccountComboBox.setItems(FXCollections.observableArrayList(user.getBankAccounts())); bankAccountComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(BankAccount bankAccount) + public String toString(@NotNull BankAccount bankAccount) { return bankAccount.getAccountTitle(); } + @Nullable @Override public BankAccount fromString(String s) { @@ -675,26 +698,23 @@ public class SettingsController implements Initializable, ChildController, Navig bankAccountComboBox.getSelectionModel().select(index); } } - else - { - bankAccountComboBox.setPromptText("No bank account available"); - bankAccountComboBox.setDisable(true); - } } private void initBankAccountTypesComboBox() { - bankAccountTypesComboBox.setItems(FXCollections.observableArrayList(BankAccountTypeInfo.getAllBankAccountTypeInfoObjects())); - bankAccountTypesComboBox.setConverter(new StringConverter() + bankAccountTypesComboBox.setItems(FXCollections.observableArrayList(BankAccountType.getAllBankAccountTypes())); + bankAccountTypesComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(BankAccountTypeInfo bankAccountTypeInfo) + public String toString(@NotNull BankAccountType bankAccountTypeInfo) { - return Localisation.get(bankAccountTypeInfo.getType().toString()); + return Localisation.get(bankAccountTypeInfo.toString()); } + @Nullable @Override - public BankAccountTypeInfo fromString(String s) + public BankAccountType fromString(String s) { return null; } @@ -703,7 +723,7 @@ public class SettingsController implements Initializable, ChildController, Navig BankAccount currentBankAccount = user.getCurrentBankAccount(); if (currentBankAccount != null) { - int index = bankAccountTypesComboBox.getItems().indexOf(currentBankAccount.getBankAccountTypeInfo()); + int index = bankAccountTypesComboBox.getItems().indexOf(currentBankAccount.getBankAccountType()); bankAccountTypesComboBox.getSelectionModel().select(index); } } @@ -713,12 +733,14 @@ public class SettingsController implements Initializable, ChildController, Navig bankAccountCurrencyComboBox.setItems(FXCollections.observableArrayList(CurrencyUtil.getAllCurrencies())); bankAccountCurrencyComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(Currency currency) + public String toString(@NotNull Currency currency) { return currency.getCurrencyCode() + " (" + currency.getDisplayName() + ")"; } + @Nullable @Override public Currency fromString(String s) { @@ -741,11 +763,12 @@ public class SettingsController implements Initializable, ChildController, Navig bankAccountRegionComboBox.setConverter(new StringConverter() { @Override - public String toString(Region region) + public String toString(@NotNull Region region) { return region.getName(); } + @Nullable @Override public Region fromString(String s) { @@ -755,12 +778,14 @@ public class SettingsController implements Initializable, ChildController, Navig bankAccountCountryComboBox.setConverter(new StringConverter() { + @NotNull @Override - public String toString(Country country) + public String toString(@NotNull Country country) { return country.getName(); } + @Nullable @Override public Country fromString(String s) { @@ -786,7 +811,7 @@ public class SettingsController implements Initializable, ChildController, Navig { if (verifyBankAccountData()) { - BankAccount bankAccount = new BankAccount( + @NotNull BankAccount bankAccount = new BankAccount( bankAccountTypesComboBox.getSelectionModel().getSelectedItem(), bankAccountCurrencyComboBox.getSelectionModel().getSelectedItem(), bankAccountCountryComboBox.getSelectionModel().getSelectedItem(), @@ -796,7 +821,7 @@ public class SettingsController implements Initializable, ChildController, Navig bankAccountSecondaryIDTextField.getText()); user.addBankAccount(bankAccount); - storage.write(user.getClass().getName(), user); + saveUser(); initBankAccountScreen(); } @@ -806,8 +831,8 @@ public class SettingsController implements Initializable, ChildController, Navig { user.removeCurrentBankAccount(); - storage.write(user.getClass().getName(), user); - + saveUser(); + saveSettings(); initBankAccountScreen(); } @@ -817,7 +842,7 @@ public class SettingsController implements Initializable, ChildController, Navig { BitSquareValidator.textFieldsNotEmptyWithReset(bankAccountTitleTextField, bankAccountHolderNameTextField, bankAccountPrimaryIDTextField, bankAccountSecondaryIDTextField); - BankAccountTypeInfo bankAccountTypeInfo = bankAccountTypesComboBox.getSelectionModel().getSelectedItem(); + BankAccountType bankAccountTypeInfo = bankAccountTypesComboBox.getSelectionModel().getSelectedItem(); BitSquareValidator.textFieldBankAccountPrimaryIDIsValid(bankAccountPrimaryIDTextField, bankAccountTypeInfo); BitSquareValidator.textFieldBankAccountSecondaryIDIsValid(bankAccountSecondaryIDTextField, bankAccountTypeInfo); diff --git a/src/main/java/io/bitsquare/gui/settings/SettingsView.fxml b/src/main/java/io/bitsquare/gui/settings/SettingsView.fxml index 010e25ab3e..7983637065 100644 --- a/src/main/java/io/bitsquare/gui/settings/SettingsView.fxml +++ b/src/main/java/io/bitsquare/gui/settings/SettingsView.fxml @@ -49,42 +49,6 @@ - -