fixed utest, update formatting added comments

This commit is contained in:
Manfred Karrer 2014-08-26 17:32:43 +02:00
parent 25b2afc545
commit 98c6e34b23
50 changed files with 286 additions and 368 deletions

View file

@ -239,12 +239,6 @@
<version>13.0</version> <version>13.0</version>
</dependency> </dependency>
<dependency>
<groupId>net.glxn</groupId>
<artifactId>qrgen</artifactId>
<version>1.3</version>
</dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId> <artifactId>mockito-all</artifactId>

View file

@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Well known node which is reachable for all peers for bootstrapping. * Well known node which is reachable for all peers for bootstrapping.
* There will be several SeedNodes running on several servers. * There will be several SeedNodes running on several servers.
* <p/> * <p>
* TODO: Alternative bootstrap methods will follow later (save locally list of known nodes reported form other peers...) * TODO: Alternative bootstrap methods will follow later (save locally list of known nodes reported form other peers...)
*/ */
public class SeedNode extends Thread { public class SeedNode extends Thread {

View file

@ -35,12 +35,18 @@ public class BankAccount implements Serializable {
private final String accountSecondaryID; // like BIC private final String accountSecondaryID; // like BIC
private final String accountHolderName; private final String accountHolderName;
private final Country country; // where bank is registered private final Country country; // where bank is registered
// The main currency if account support multiple currencies. // The main currency if account support multiple currencies.
// The user can create multiple bank accounts with same bank account but other currency if his bank account // The user can create multiple bank accounts with same bank account but other currency if his bank account
// support that. // support that.
private final Currency currency; private final Currency currency;
private final String accountTitle; private final String accountTitle;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////
public BankAccount(BankAccountType bankAccountType, Currency currency, Country country, String accountTitle, public BankAccount(BankAccountType bankAccountType, Currency currency, Country country, String accountTitle,
String accountHolderName, String accountPrimaryID, String accountSecondaryID) { String accountHolderName, String accountPrimaryID, String accountSecondaryID) {
this.bankAccountType = bankAccountType; this.bankAccountType = bankAccountType;
@ -52,18 +58,10 @@ public class BankAccount implements Serializable {
this.accountSecondaryID = accountSecondaryID; this.accountSecondaryID = accountSecondaryID;
} }
public int hashCode() {
return Objects.hashCode(accountTitle);
}
public boolean equals(Object obj) {
if (!(obj instanceof BankAccount)) return false;
if (obj == this) return true;
final BankAccount other = (BankAccount) obj;
return accountTitle.equals(other.getUid());
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getters/Setters
///////////////////////////////////////////////////////////////////////////////////////////
public String getAccountPrimaryID() { public String getAccountPrimaryID() {
return accountPrimaryID; return accountPrimaryID;
@ -98,6 +96,25 @@ public class BankAccount implements Serializable {
return accountTitle; return accountTitle;
} }
///////////////////////////////////////////////////////////////////////////////////////////
// Methods
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public int hashCode() {
return Objects.hashCode(accountTitle);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BankAccount)) return false;
if (obj == this) return true;
final BankAccount other = (BankAccount) obj;
return accountTitle.equals(other.getUid());
}
@Override @Override
public String toString() { public String toString() {
return "BankAccount{" + return "BankAccount{" +

View file

@ -24,6 +24,10 @@ import com.google.bitcoin.crypto.DeterministicKey;
import java.io.Serializable; import java.io.Serializable;
/**
* Is a minimalistic wallet abstraction used to separate transactions between different activities like:
* Registration, trade and arbiter deposit.
*/
public class AddressEntry implements Serializable { public class AddressEntry implements Serializable {
private static final long serialVersionUID = 5501603992599920416L; private static final long serialVersionUID = 5501603992599920416L;
private transient DeterministicKey key; private transient DeterministicKey key;

View file

@ -23,6 +23,7 @@ import com.google.bitcoin.core.Transaction;
import javax.inject.Inject; import javax.inject.Inject;
// TODO will be probably removed
public class BtcValidator { public class BtcValidator {
private static NetworkParameters params; private static NetworkParameters params;

View file

@ -34,6 +34,8 @@ public class FeePolicy {
public static final Coin CREATE_OFFER_FEE = Coin.MILLICOIN; // 0.001 public static final Coin CREATE_OFFER_FEE = Coin.MILLICOIN; // 0.001
public static final Coin TAKE_OFFER_FEE = CREATE_OFFER_FEE; public static final Coin TAKE_OFFER_FEE = CREATE_OFFER_FEE;
private static final Logger log = LoggerFactory.getLogger(FeePolicy.class); private static final Logger log = LoggerFactory.getLogger(FeePolicy.class);
// those are just dummy yet. trading fees will go probably to arbiters
private static final String registrationFeeAddress = "mvkDXt4QmN4Nq9dRUsRigBCaovde9nLkZR"; private static final String registrationFeeAddress = "mvkDXt4QmN4Nq9dRUsRigBCaovde9nLkZR";
private static final String createOfferFeeAddress = "n2upbsaKAe4PD3cc4JfS7UCqPC5oNd7Ckg"; private static final String createOfferFeeAddress = "n2upbsaKAe4PD3cc4JfS7UCqPC5oNd7Ckg";
private static final String takeOfferFeeAddress = "n2upbsaKAe4PD3cc4JfS7UCqPC5oNd7Ckg"; private static final String takeOfferFeeAddress = "n2upbsaKAe4PD3cc4JfS7UCqPC5oNd7Ckg";

View file

@ -32,6 +32,5 @@ public class ConfidenceListener {
} }
public void onTransactionConfidenceChanged(TransactionConfidence confidence) { public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
} }
} }

View file

@ -103,7 +103,7 @@ public class GuiceFXMLLoader {
* A JavaFX controller factory for constructing controllers via Guice DI. To * A JavaFX controller factory for constructing controllers via Guice DI. To
* install this in the {@link javafx.fxml.FXMLLoader}, pass it as a parameter to * install this in the {@link javafx.fxml.FXMLLoader}, pass it as a parameter to
* {@link javafx.fxml.FXMLLoader#setControllerFactory(javafx.util.Callback)}. * {@link javafx.fxml.FXMLLoader#setControllerFactory(javafx.util.Callback)}.
* <p/> * <p>
* Once set, make sure you do <b>not</b> use the static methods on * Once set, make sure you do <b>not</b> use the static methods on
* {@link javafx.fxml.FXMLLoader} when creating your JavaFX node. * {@link javafx.fxml.FXMLLoader} when creating your JavaFX node.
*/ */

View file

@ -400,7 +400,7 @@ public class MainController extends ViewController {
}); });
user.getSelectedBankAccountIndexProperty().addListener(observable -> user.getSelectedBankAccountIndexProperty().addListener(observable ->
accountComboBox.getSelectionModel().select(user.getCurrentBankAccount())); accountComboBox.getSelectionModel().select(user.getCurrentBankAccount()));
user.getBankAccountsSizeProperty().addListener(observable -> { user.getBankAccountsSizeProperty().addListener(observable -> {
accountComboBox.setItems(FXCollections.observableArrayList(user.getBankAccounts())); accountComboBox.setItems(FXCollections.observableArrayList(user.getBankAccounts()));
// need to delay it a bit otherwise it will not be set // need to delay it a bit otherwise it will not be set

View file

@ -16,8 +16,7 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.scene.layout.BorderPane?> <?import javafx.scene.layout.*?>
<BorderPane fx:id="root" id="splash" fx:controller="io.bitsquare.gui.MainController" <BorderPane fx:id="root" id="splash" fx:controller="io.bitsquare.gui.MainController"
prefHeight="750" prefWidth="1000" stylesheets="/io/bitsquare/gui/bitsquare.css" prefHeight="750" prefWidth="1000" stylesheets="/io/bitsquare/gui/bitsquare.css"
xmlns:fx="http://javafx.com/fxml"> xmlns:fx="http://javafx.com/fxml">

View file

@ -16,9 +16,8 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.scene.control.Button?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.arbitrators.overview.ArbitratorOverviewController" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.arbitrators.overview.ArbitratorOverviewController"
prefHeight="600" prefWidth="800" AnchorPane.bottomAnchor="30.0" AnchorPane.leftAnchor="10.0" prefHeight="600" prefWidth="800" AnchorPane.bottomAnchor="30.0" AnchorPane.leftAnchor="10.0"
AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0"

View file

@ -128,7 +128,7 @@ public class ArbitratorProfileController extends CachedViewController {
reputationTextField.setText(arbitrator.getReputation().toString()); reputationTextField.setText(arbitrator.getReputation().toString());
maxTradeVolumeTextField.setText(String.valueOf(arbitrator.getMaxTradeVolume()) + " BTC"); maxTradeVolumeTextField.setText(String.valueOf(arbitrator.getMaxTradeVolume()) + " BTC");
passiveServiceFeeTextField.setText(String.valueOf(arbitrator.getPassiveServiceFee()) + " % (Min. " + passiveServiceFeeTextField.setText(String.valueOf(arbitrator.getPassiveServiceFee()) + " % (Min. " +
String.valueOf(arbitrator.getMinPassiveServiceFee()) + " BTC)"); String.valueOf(arbitrator.getMinPassiveServiceFee()) + " BTC)");
arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee()) + " % (Min. " + String arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee()) + " % (Min. " + String
.valueOf(arbitrator.getMinArbitrationFee()) + " BTC)"); .valueOf(arbitrator.getMinArbitrationFee()) + " BTC)");
methodsTextField.setText(BSFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods())); methodsTextField.setText(BSFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods()));

View file

@ -19,7 +19,6 @@
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<GridPane fx:id="root" fx:controller="io.bitsquare.gui.arbitrators.profile.ArbitratorProfileController" <GridPane fx:id="root" fx:controller="io.bitsquare.gui.arbitrators.profile.ArbitratorProfileController"
hgap="5.0" vgap="5.0" AnchorPane.bottomAnchor="80.0" AnchorPane.leftAnchor="10.0" hgap="5.0" vgap="5.0" AnchorPane.bottomAnchor="80.0" AnchorPane.leftAnchor="10.0"
AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0"

View file

@ -166,7 +166,7 @@ public class ArbitratorRegistrationController extends CachedViewController {
}); });
methodsComboBox.setItems(FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator.METHOD methodsComboBox.setItems(FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator.METHOD
.class)))); .class))));
methodsComboBox.setConverter(new StringConverter<Arbitrator.METHOD>() { methodsComboBox.setConverter(new StringConverter<Arbitrator.METHOD>() {
@Override @Override
@ -355,11 +355,11 @@ public class ArbitratorRegistrationController extends CachedViewController {
private void setupPayCollateralScreen() { private void setupPayCollateralScreen() {
infoLabel.setText("You need to pay 10 x the max. trading volume as collateral.\n\nThat payment will be " + infoLabel.setText("You need to pay 10 x the max. trading volume as collateral.\n\nThat payment will be " +
"locked into a MultiSig fund and be refunded when you leave the arbitration pool.\nIn case of fraud " + "locked into a MultiSig fund and be refunded when you leave the arbitration pool.\nIn case of fraud " +
"(collusion, not fulfilling the min. dispute quality requirements) you will lose your collateral.\n" + "(collusion, not fulfilling the min. dispute quality requirements) you will lose your collateral.\n" +
"If you have a negative feedback from your clients you will lose a part of the collateral,\n" + "If you have a negative feedback from your clients you will lose a part of the collateral,\n" +
"depending on the overall relation of negative to positive ratings you received after a dispute " + "depending on the overall relation of negative to positive ratings you received after a dispute " +
"resolution.\n\nPlease pay in " + arbitrator.getMaxTradeVolume() * 10 + " BTC"); "resolution.\n\nPlease pay in " + arbitrator.getMaxTradeVolume() * 10 + " BTC");
String collateralAddress = walletFacade.getRegistrationAddressEntry() != null ? String collateralAddress = walletFacade.getRegistrationAddressEntry() != null ?
@ -476,20 +476,20 @@ public class ArbitratorRegistrationController extends CachedViewController {
String description = descriptionTextArea.getText(); String description = descriptionTextArea.getText();
return new Arbitrator(pubKeyAsHex, return new Arbitrator(pubKeyAsHex,
messagePubKeyAsHex, messagePubKeyAsHex,
name, name,
idType, idType,
languageList, languageList,
new Reputation(), new Reputation(),
maxTradeVolume, maxTradeVolume,
passiveServiceFee, passiveServiceFee,
minPassiveServiceFee, minPassiveServiceFee,
arbitrationFee, arbitrationFee,
minArbitrationFee, minArbitrationFee,
methodList, methodList,
idVerificationList, idVerificationList,
webUrl, webUrl,
description); description);
} catch (BitSquareValidator.ValidationException e) { } catch (BitSquareValidator.ValidationException e) {
return null; return null;
} }

View file

@ -20,7 +20,6 @@
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.arbitrators.registration.ArbitratorRegistrationController" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.arbitrators.registration.ArbitratorRegistrationController"
prefHeight="600" prefWidth="800" AnchorPane.bottomAnchor="30.0" AnchorPane.leftAnchor="10.0" prefHeight="600" prefWidth="800" AnchorPane.bottomAnchor="30.0" AnchorPane.leftAnchor="10.0"
AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0"

View file

@ -38,7 +38,7 @@ import org.slf4j.LoggerFactory;
* TextField with validation support. Validation is executed on the Validator object. * TextField with validation support. Validation is executed on the Validator object.
* In case of a invalid result we display a error message with a PopOver. * In case of a invalid result we display a error message with a PopOver.
* The position is derived from the textField or if set from the errorPopupLayoutReference object. * The position is derived from the textField or if set from the errorPopupLayoutReference object.
* <p/> * <p>
* That class implements just what we need for the moment. It is not intended as a general purpose library class. * That class implements just what we need for the moment. It is not intended as a general purpose library class.
*/ */
public class ValidatingTextField extends TextField { public class ValidatingTextField extends TextField {

View file

@ -149,7 +149,7 @@ public class AddressTextField extends AnchorPane {
this.paymentLabel = paymentLabel; this.paymentLabel = paymentLabel;
} }
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Private // Private
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////

View file

@ -43,22 +43,22 @@ import javafx.scene.control.*;
* <p> * <p>
* ProgressIndicator sets focusTraversable to false. * ProgressIndicator sets focusTraversable to false.
* </p> * </p>
* <p/> * <p>
* <p/> * <p>
* This first example creates a ProgressIndicator with an indeterminate value : * This first example creates a ProgressIndicator with an indeterminate value :
* <pre><code> * <pre><code>
* import javafx.scene.control.ProgressIndicator; * import javafx.scene.control.ProgressIndicator;
* ProgressIndicator p1 = new ProgressIndicator(); * ProgressIndicator p1 = new ProgressIndicator();
* </code></pre> * </code></pre>
* <p/> * <p>
* <p/> * <p>
* This next example creates a ProgressIndicator which is 25% complete : * This next example creates a ProgressIndicator which is 25% complete :
* <pre><code> * <pre><code>
* import javafx.scene.control.ProgressIndicator; * import javafx.scene.control.ProgressIndicator;
* ProgressIndicator p2 = new ProgressIndicator(); * ProgressIndicator p2 = new ProgressIndicator();
* p2.setProgress(0.25F); * p2.setProgress(0.25F);
* </code></pre> * </code></pre>
* <p/> * <p>
* Implementation of ProgressIndicator According to JavaFX UI Control API Specification * Implementation of ProgressIndicator According to JavaFX UI Control API Specification
* *
* @since JavaFX 2.0 * @since JavaFX 2.0
@ -81,7 +81,7 @@ public class ConfidenceProgressIndicator extends Control {
**************************************************************************/ **************************************************************************/
/** /**
* Initialize the style class to 'progress-indicator'. * Initialize the style class to 'progress-indicator'.
* <p/> * <p>
* This is the selector class from which CSS can be used to style * This is the selector class from which CSS can be used to style
* this control. * this control.
*/ */

View file

@ -17,9 +17,8 @@
--> -->
<?import io.bitsquare.gui.components.CachingTabPane?> <?import io.bitsquare.gui.components.CachingTabPane?>
<?import javafx.scene.control.Tab?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.*?>
<CachingTabPane fx:id="root" fx:controller="io.bitsquare.gui.funds.FundsController" <CachingTabPane fx:id="root" fx:controller="io.bitsquare.gui.funds.FundsController"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0" AnchorPane.topAnchor="0.0"

View file

@ -18,10 +18,9 @@
--> -->
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.cell.*?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.PropertyValueFactory?> <?import javafx.scene.layout.*?>
<?import javafx.scene.layout.VBox?>
<VBox fx:id="root" fx:controller="io.bitsquare.gui.funds.deposit.DepositController" <VBox fx:id="root" fx:controller="io.bitsquare.gui.funds.deposit.DepositController"
spacing="10" xmlns:fx="http://javafx.com/fxml"> spacing="10" xmlns:fx="http://javafx.com/fxml">
<padding> <padding>

View file

@ -18,10 +18,9 @@
--> -->
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.cell.PropertyValueFactory?> <?import javafx.scene.control.cell.*?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.VBox?> <?import javafx.scene.layout.*?>
<VBox fx:id="root" fx:controller="io.bitsquare.gui.funds.transactions.TransactionsController" <VBox fx:id="root" fx:controller="io.bitsquare.gui.funds.transactions.TransactionsController"
spacing="10" xmlns:fx="http://javafx.com/fxml"> spacing="10" xmlns:fx="http://javafx.com/fxml">
<padding> <padding>

View file

@ -131,7 +131,7 @@ public class WithdrawalController extends CachedViewController {
List<AddressEntry> addressEntryList = walletFacade.getAddressEntryList(); List<AddressEntry> addressEntryList = walletFacade.getAddressEntryList();
addressList = FXCollections.observableArrayList(); addressList = FXCollections.observableArrayList();
addressList.addAll(addressEntryList.stream().map(anAddressEntryList -> addressList.addAll(addressEntryList.stream().map(anAddressEntryList ->
new WithdrawalListItem(anAddressEntryList, walletFacade)).collect(Collectors.toList())); new WithdrawalListItem(anAddressEntryList, walletFacade)).collect(Collectors.toList()));
tableView.setItems(addressList); tableView.setItems(addressList);
} }
@ -182,7 +182,7 @@ public class WithdrawalController extends CachedViewController {
changeAddressTextField.getText(), amount, callback); changeAddressTextField.getText(), amount, callback);
} catch (AddressFormatException e) { } catch (AddressFormatException e) {
Popups.openErrorPopup("Address invalid", Popups.openErrorPopup("Address invalid",
"The address is not correct. Please check the address format."); "The address is not correct. Please check the address format.");
} catch (InsufficientMoneyException e) { } catch (InsufficientMoneyException e) {
Popups.openInsufficientMoneyPopup(); Popups.openInsufficientMoneyPopup();
@ -194,7 +194,7 @@ public class WithdrawalController extends CachedViewController {
} }
else { else {
Popups.openErrorPopup("Insufficient amount", Popups.openErrorPopup("Insufficient amount",
"The amount to transfer is lower the the transaction fee and the min. possible tx value."); "The amount to transfer is lower the the transaction fee and the min. possible tx value.");
} }
} catch (BitSquareValidator.ValidationException e) { } catch (BitSquareValidator.ValidationException e) {
@ -308,7 +308,7 @@ public class WithdrawalController extends CachedViewController {
private void setConfidenceColumnCellFactory() { private void setConfidenceColumnCellFactory() {
confidenceColumn.setCellValueFactory((addressListItem) -> confidenceColumn.setCellValueFactory((addressListItem) ->
new ReadOnlyObjectWrapper(addressListItem.getValue())); new ReadOnlyObjectWrapper(addressListItem.getValue()));
confidenceColumn.setCellFactory( confidenceColumn.setCellFactory(
new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, WithdrawalListItem>>() { new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, WithdrawalListItem>>() {

View file

@ -19,9 +19,8 @@
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.PropertyValueFactory?> <?import javafx.scene.control.cell.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<VBox fx:id="root" fx:controller="io.bitsquare.gui.funds.withdrawal.WithdrawalController" <VBox fx:id="root" fx:controller="io.bitsquare.gui.funds.withdrawal.WithdrawalController"
spacing="10" xmlns:fx="http://javafx.com/fxml"> spacing="10" xmlns:fx="http://javafx.com/fxml">
<padding> <padding>

View file

@ -17,10 +17,8 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.scene.control.Button?> <?import javafx.scene.control.*?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.home.HomeController" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.home.HomeController"
AnchorPane.bottomAnchor="30" AnchorPane.leftAnchor="10" AnchorPane.rightAnchor="10" AnchorPane.bottomAnchor="30" AnchorPane.leftAnchor="10" AnchorPane.rightAnchor="10"
AnchorPane.topAnchor="10" AnchorPane.topAnchor="10"

View file

@ -17,9 +17,8 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.scene.control.Label?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.msg.MsgController" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.msg.MsgController"
AnchorPane.bottomAnchor="0" AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.topAnchor="0" AnchorPane.bottomAnchor="0" AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.topAnchor="0"
xmlns:fx="http://javafx.com/fxml"> xmlns:fx="http://javafx.com/fxml">

View file

@ -18,9 +18,8 @@
--> -->
<?import io.bitsquare.gui.components.CachingTabPane?> <?import io.bitsquare.gui.components.CachingTabPane?>
<?import javafx.scene.control.Tab?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.*?>
<CachingTabPane fx:id="root" fx:controller="io.bitsquare.gui.orders.OrdersController" <CachingTabPane fx:id="root" fx:controller="io.bitsquare.gui.orders.OrdersController"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0" AnchorPane.topAnchor="0.0"

View file

@ -17,9 +17,8 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.scene.control.Label?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.orders.closed.ClosedTradeController" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.orders.closed.ClosedTradeController"
AnchorPane.bottomAnchor="0" AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.topAnchor="0" AnchorPane.bottomAnchor="0" AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.topAnchor="0"
xmlns:fx="http://javafx.com/fxml"> xmlns:fx="http://javafx.com/fxml">

View file

@ -20,8 +20,7 @@
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.cell.*?> <?import javafx.scene.control.cell.*?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.VBox?> <?import javafx.scene.layout.*?>
<VBox fx:id="root" fx:controller="io.bitsquare.gui.orders.offer.OfferController" <VBox fx:id="root" fx:controller="io.bitsquare.gui.orders.offer.OfferController"
spacing="10" xmlns:fx="http://javafx.com/fxml"> spacing="10" xmlns:fx="http://javafx.com/fxml">
<padding> <padding>

View file

@ -157,8 +157,8 @@ public class PendingTradeController extends CachedViewController {
// select // select
Optional<PendingTradesListItem> currentTradeItemOptional = tradeItems.stream().filter((e) -> Optional<PendingTradesListItem> currentTradeItemOptional = tradeItems.stream().filter((e) ->
tradeManager.getPendingTrade() != null && tradeManager.getPendingTrade() != null &&
e.getTrade().getId().equals(tradeManager.getPendingTrade().getId())).findFirst(); e.getTrade().getId().equals(tradeManager.getPendingTrade().getId())).findFirst();
if (currentTradeItemOptional.isPresent()) { if (currentTradeItemOptional.isPresent()) {
openTradesTable.getSelectionModel().select(currentTradeItemOptional.get()); openTradesTable.getSelectionModel().select(currentTradeItemOptional.get());
} }
@ -241,7 +241,7 @@ public class PendingTradeController extends CachedViewController {
Transaction transaction = trade.getDepositTransaction(); Transaction transaction = trade.getDepositTransaction();
if (transaction == null) { if (transaction == null) {
trade.depositTxChangedProperty().addListener((observableValue, aBoolean, aBoolean2) -> trade.depositTxChangedProperty().addListener((observableValue, aBoolean, aBoolean2) ->
updateTx(trade.getDepositTransaction())); updateTx(trade.getDepositTransaction()));
} }
else { else {
updateTx(trade.getDepositTransaction()); updateTx(trade.getDepositTransaction());
@ -370,8 +370,8 @@ public class PendingTradeController extends CachedViewController {
} catch (Exception e) { } catch (Exception e) {
log.warn("Country icon not found: /images/countries/" + log.warn("Country icon not found: /images/countries/" +
country.getCode().toLowerCase() + ".png country name: " + country.getCode().toLowerCase() + ".png country name: " +
country.getName()); country.getName());
} }
Tooltip.install(this, new Tooltip(country.getName())); Tooltip.install(this, new Tooltip(country.getName()));
} }
@ -395,7 +395,7 @@ public class PendingTradeController extends CachedViewController {
if (tradesTableItem != null) { if (tradesTableItem != null) {
BankAccountType bankAccountType = tradesTableItem.getTrade().getOffer() BankAccountType bankAccountType = tradesTableItem.getTrade().getOffer()
.getBankAccountType(); .getBankAccountType();
setText(Localisation.get(bankAccountType.toString())); setText(Localisation.get(bankAccountType.toString()));
} }
else { else {

View file

@ -18,11 +18,10 @@
--> -->
<?import io.bitsquare.gui.components.confidence.ConfidenceProgressIndicator?> <?import io.bitsquare.gui.components.confidence.ConfidenceProgressIndicator?>
<?import javafx.geometry.*?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.PropertyValueFactory?> <?import javafx.scene.control.cell.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<VBox fx:id="root" fx:controller="io.bitsquare.gui.orders.pending.PendingTradeController" <VBox fx:id="root" fx:controller="io.bitsquare.gui.orders.pending.PendingTradeController"
spacing="10" AnchorPane.bottomAnchor="0" spacing="10" AnchorPane.bottomAnchor="0"
AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.topAnchor="0" AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.topAnchor="0"

View file

@ -20,7 +20,6 @@
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<TabPane fx:id="root" fx:controller="io.bitsquare.gui.settings.SettingsController" <TabPane fx:id="root" fx:controller="io.bitsquare.gui.settings.SettingsController"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0" AnchorPane.topAnchor="0.0"

View file

@ -17,9 +17,8 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.scene.control.TabPane?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.*?>
<TabPane fx:id="root" fx:controller="io.bitsquare.gui.trade.BuyController" <TabPane fx:id="root" fx:controller="io.bitsquare.gui.trade.BuyController"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0" AnchorPane.topAnchor="0.0"

View file

@ -17,9 +17,8 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.scene.control.TabPane?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.*?>
<TabPane fx:id="root" fx:controller="io.bitsquare.gui.trade.SellController" <TabPane fx:id="root" fx:controller="io.bitsquare.gui.trade.SellController"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0" AnchorPane.topAnchor="0.0"

View file

@ -76,7 +76,7 @@ public class TradeController extends CachedViewController {
// TODO find better solution // TODO find better solution
// Textfield focus out triggers validation, use runLater as quick fix... // Textfield focus out triggers validation, use runLater as quick fix...
((TabPane) root).getSelectionModel().selectedIndexProperty().addListener((observableValue) -> ((TabPane) root).getSelectionModel().selectedIndexProperty().addListener((observableValue) ->
Platform.runLater(() -> ValidatingTextField.hidePopover())); Platform.runLater(() -> ValidatingTextField.hidePopover()));
} }

View file

@ -39,27 +39,26 @@ import javafx.scene.layout.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
//TODO check DI
/** /**
* Code behind (FXML Controller is part of View, not a classical controller from MVC): * Code behind (FXML Controller is part of View, not a classical controller from MVC):
* <p> * <p>
* Creates Presenter and passes Model from DI to Presenter. Does not hold a reference to Model * Creates Presenter and passes Model from DI to Presenter. Does not hold a reference to Model
* <p> * <p>
* - Setup binding from Presenter to View elements (also bidirectional - Inputs). Binding are only to presenters properties, not logical bindings or cross-view element bindings. * - Setup binding from Presenter to View elements (also bidirectional - Inputs). Binding are only to presenters
* properties, not logical bindings or cross-view element bindings.
* - Listen to UI events (Action) from View and call method in Presenter. * - Listen to UI events (Action) from View and call method in Presenter.
* - Is entry node for hierarchical view graphs. Passes method calls to Presenter. Calls methods on sub views. * - Is entry node for hierarchical view graphs. Passes method calls to Presenter. Calls methods on sub views.
* - Handle lifecycle and self removal from scene graph. * - Handle lifecycle and self removal from scene graph.
* - Non declarative (dynamic) view definitions (if it gets larger, then user a ViewBuilder) * - Non declarative (dynamic) view definitions (if it gets larger, then user a ViewBuilder)
* <p> * <p>
* View: * View:
* - Mostly declared in FXML. Dynamic parts are declared in Controller. If more view elements need to be defined in code then use ViewBuilder. * - Mostly declared in FXML. Dynamic parts are declared in Controller. If more view elements need to be defined in
* code then use ViewBuilder.
* <p> * <p>
* Optional ViewBuilder: * Optional ViewBuilder:
* - Replacement for FXML view definitions. * - Replacement for FXML view definitions.
*/ */
public class CreateOfferCodeBehind extends CachedViewController public class CreateOfferCodeBehind extends CachedViewController {
{
private static final Logger log = LoggerFactory.getLogger(CreateOfferCodeBehind.class); private static final Logger log = LoggerFactory.getLogger(CreateOfferCodeBehind.class);
private final CreateOfferPresenter presenter; private final CreateOfferPresenter presenter;
@ -69,7 +68,9 @@ public class CreateOfferCodeBehind extends CachedViewController
@FXML private ValidatingTextField amountTextField, minAmountTextField, priceTextField, volumeTextField; @FXML private ValidatingTextField amountTextField, minAmountTextField, priceTextField, volumeTextField;
@FXML private Button placeOfferButton, closeButton; @FXML private Button placeOfferButton, closeButton;
@FXML private TextField totalToPayTextField, collateralTextField, bankAccountTypeTextField, bankAccountCurrencyTextField, bankAccountCountyTextField, acceptedCountriesTextField, acceptedLanguagesTextField, @FXML private TextField totalToPayTextField, collateralTextField, bankAccountTypeTextField,
bankAccountCurrencyTextField, bankAccountCountyTextField, acceptedCountriesTextField,
acceptedLanguagesTextField,
feeLabel, transactionIdTextField; feeLabel, transactionIdTextField;
@FXML private ConfidenceProgressIndicator progressIndicator; @FXML private ConfidenceProgressIndicator progressIndicator;
@FXML private AddressTextField addressTextField; @FXML private AddressTextField addressTextField;
@ -81,8 +82,7 @@ public class CreateOfferCodeBehind extends CachedViewController
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
public CreateOfferCodeBehind(CreateOfferModel model) public CreateOfferCodeBehind(CreateOfferModel model) {
{
presenter = new CreateOfferPresenter(model); presenter = new CreateOfferPresenter(model);
} }
@ -92,23 +92,20 @@ public class CreateOfferCodeBehind extends CachedViewController
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
public void initialize(URL url, ResourceBundle rb) public void initialize(URL url, ResourceBundle rb) {
{
super.initialize(url, rb); super.initialize(url, rb);
presenter.onViewInitialized(); presenter.onViewInitialized();
} }
@Override @Override
public void deactivate() public void deactivate() {
{
super.deactivate(); super.deactivate();
presenter.deactivate(); presenter.deactivate();
((TradeController) parentController).onCreateOfferViewRemoved(); ((TradeController) parentController).onCreateOfferViewRemoved();
} }
@Override @Override
public void activate() public void activate() {
{
super.activate(); super.activate();
presenter.activate(); presenter.activate();
@ -129,8 +126,7 @@ public class CreateOfferCodeBehind extends CachedViewController
// Public methods // Public methods
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void setOrderBookFilter(OrderBookFilter orderBookFilter) public void setOrderBookFilter(OrderBookFilter orderBookFilter) {
{
presenter.setOrderBookFilter(orderBookFilter); presenter.setOrderBookFilter(orderBookFilter);
} }
@ -139,14 +135,12 @@ public class CreateOfferCodeBehind extends CachedViewController
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@FXML @FXML
public void onPlaceOffer() public void onPlaceOffer() {
{
presenter.placeOffer(); presenter.placeOffer();
} }
@FXML @FXML
public void onClose() public void onClose() {
{
presenter.close(); presenter.close();
TabPane tabPane = ((TabPane) (rootContainer.getParent().getParent())); TabPane tabPane = ((TabPane) (rootContainer.getParent().getParent()));
@ -158,15 +152,19 @@ public class CreateOfferCodeBehind extends CachedViewController
// Private Methods // Private Methods
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void setupListeners() private void setupListeners() {
{ volumeTextField.focusedProperty().addListener((observableValue, oldValue,
volumeTextField.focusedProperty().addListener((observableValue, oldValue, newValue) -> presenter.checkVolumeOnFocusOut(oldValue, newValue, volumeTextField.getText())); newValue) -> presenter.checkVolumeOnFocusOut(oldValue,
amountTextField.focusedProperty().addListener((observableValue, oldValue, newValue) -> presenter.onFocusOutAmountTextField(oldValue, newValue)); newValue, volumeTextField.getText()));
priceTextField.focusedProperty().addListener((observableValue, oldValue, newValue) -> presenter.onFocusOutPriceTextField(oldValue, newValue)); amountTextField.focusedProperty().addListener((observableValue, oldValue,
newValue) -> presenter.onFocusOutAmountTextField(oldValue,
newValue));
priceTextField.focusedProperty().addListener((observableValue, oldValue,
newValue) -> presenter.onFocusOutPriceTextField(oldValue,
newValue));
presenter.validateInput.addListener((o, oldValue, newValue) -> { presenter.validateInput.addListener((o, oldValue, newValue) -> {
if (newValue) if (newValue) {
{
amountTextField.reValidate(); amountTextField.reValidate();
minAmountTextField.reValidate(); minAmountTextField.reValidate();
volumeTextField.reValidate(); volumeTextField.reValidate();
@ -175,16 +173,15 @@ public class CreateOfferCodeBehind extends CachedViewController
}); });
presenter.showVolumeAdjustedWarning.addListener((o, oldValue, newValue) -> { presenter.showVolumeAdjustedWarning.addListener((o, oldValue, newValue) -> {
if (newValue) if (newValue) {
{ Popups.openWarningPopup("Warning", "The total volume you have entered leads to invalid fractional " +
Popups.openWarningPopup("Warning", "The total volume you have entered leads to invalid fractional Bitcoin amounts.\nThe amount has been adjusted and a new total volume be calculated from it."); "Bitcoin amounts.\nThe amount has been adjusted and a new total volume be calculated from it.");
volumeTextField.setText(presenter.volume.get()); volumeTextField.setText(presenter.volume.get());
} }
}); });
} }
private void setupBindings() private void setupBindings() {
{
buyLabel.textProperty().bind(presenter.directionLabel); buyLabel.textProperty().bind(presenter.directionLabel);
amountTextField.textProperty().bindBidirectional(presenter.amount); amountTextField.textProperty().bindBidirectional(presenter.amount);
priceTextField.textProperty().bindBidirectional(presenter.price); priceTextField.textProperty().bindBidirectional(presenter.price);
@ -221,8 +218,7 @@ public class CreateOfferCodeBehind extends CachedViewController
.and(priceTextField.isValidProperty()).not());*/ .and(priceTextField.isValidProperty()).not());*/
} }
private void setupTextFieldValidators() private void setupTextFieldValidators() {
{
/* BtcValidator amountValidator = new BtcValidator(); /* BtcValidator amountValidator = new BtcValidator();
amountTextField.setNumberValidator(amountValidator); amountTextField.setNumberValidator(amountValidator);
amountTextField.setErrorPopupLayoutReference((Region) amountTextField.getParent()); amountTextField.setErrorPopupLayoutReference((Region) amountTextField.getParent());

View file

@ -59,8 +59,7 @@ import static com.google.common.base.Preconditions.checkArgument;
* - Holds domain data * - Holds domain data
* - Use Properties for bindable data * - Use Properties for bindable data
*/ */
class CreateOfferModel class CreateOfferModel {
{
private static final Logger log = LoggerFactory.getLogger(CreateOfferModel.class); private static final Logger log = LoggerFactory.getLogger(CreateOfferModel.class);
private final TradeManager tradeManager; private final TradeManager tradeManager;
@ -68,8 +67,7 @@ class CreateOfferModel
private final Settings settings; private final Settings settings;
private final User user; private final User user;
String getOfferId() String getOfferId() {
{
return offerId; return offerId;
} }
@ -106,8 +104,7 @@ class CreateOfferModel
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
CreateOfferModel(TradeManager tradeManager, WalletFacade walletFacade, Settings settings, User user) CreateOfferModel(TradeManager tradeManager, WalletFacade walletFacade, Settings settings, User user) {
{
this.tradeManager = tradeManager; this.tradeManager = tradeManager;
this.walletFacade = walletFacade; this.walletFacade = walletFacade;
this.settings = settings; this.settings = settings;
@ -115,7 +112,8 @@ class CreateOfferModel
offerId = UUID.randomUUID().toString(); offerId = UUID.randomUUID().toString();
totalFeesAsCoin = FeePolicy.CREATE_OFFER_FEE.add(FeePolicy.TX_FEE); totalFeesAsCoin = FeePolicy.CREATE_OFFER_FEE.add(FeePolicy.TX_FEE);
if (walletFacade != null && walletFacade.getWallet() != null) addressEntry = walletFacade.getAddressInfoByTradeID(offerId); if (walletFacade != null && walletFacade.getWallet() != null)
addressEntry = walletFacade.getAddressInfoByTradeID(offerId);
} }
@ -123,13 +121,11 @@ class CreateOfferModel
// Methods // Methods
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
void activate() void activate() {
{
collateralAsLong.set(settings.getCollateral()); collateralAsLong.set(settings.getCollateral());
BankAccount bankAccount = user.getCurrentBankAccount(); BankAccount bankAccount = user.getCurrentBankAccount();
if (bankAccount != null) if (bankAccount != null) {
{
bankAccountType.set(bankAccount.getBankAccountType().toString()); bankAccountType.set(bankAccount.getBankAccountType().toString());
bankAccountCurrency.set(bankAccount.getCurrency().getCurrencyCode()); bankAccountCurrency.set(bankAccount.getCurrency().getCurrencyCode());
bankAccountCounty.set(bankAccount.getCountry().getName()); bankAccountCounty.set(bankAccount.getCountry().getName());
@ -138,22 +134,21 @@ class CreateOfferModel
acceptedLanguages.setAll(settings.getAcceptedLanguageLocales()); acceptedLanguages.setAll(settings.getAcceptedLanguageLocales());
} }
void placeOffer() void placeOffer() {
{
tradeManager.requestPlaceOffer(offerId, tradeManager.requestPlaceOffer(offerId,
direction, direction,
priceAsFiat.value, priceAsFiat.value,
amountAsCoin, amountAsCoin,
minAmountAsCoin, minAmountAsCoin,
(transaction) -> { (transaction) -> {
requestPlaceOfferSuccess.set(true); requestPlaceOfferSuccess.set(true);
transactionId.set(transaction.getHashAsString()); transactionId.set(transaction.getHashAsString());
}, },
(errorMessage) -> { (errorMessage) -> {
requestPlaceOfferFailed.set(true); requestPlaceOfferFailed.set(true);
requestPlaceOfferErrorMessage.set(errorMessage); requestPlaceOfferErrorMessage.set(errorMessage);
} }
); );
} }
@ -161,13 +156,11 @@ class CreateOfferModel
// Setter/Getter // Setter/Getter
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
Direction getDirection() Direction getDirection() {
{
return direction; return direction;
} }
void setDirection(Direction direction) void setDirection(Direction direction) {
{
// direction must not be changed once it is initially set // direction must not be changed once it is initially set
checkArgument(this.direction == null); checkArgument(this.direction == null);
this.direction = direction; this.direction = direction;

View file

@ -45,11 +45,12 @@ import static javafx.beans.binding.Bindings.createStringBinding;
* Knows Model, does not know the View (CodeBehind) * Knows Model, does not know the View (CodeBehind)
* <p> * <p>
* - Holds data and state of the View (formatted) * - Holds data and state of the View (formatted)
* - Receive view input from Controller. Validates input, apply business logic, format to Presenter properties and convert input to Model. * - Receive view input from Controller. Validates input, apply business logic, format to Presenter properties and
* - Listen to updates from Model, apply business logic and format it to Presenter properties. Model update handling can be done via Binding. * convert input to Model.
* - Listen to updates from Model, apply business logic and format it to Presenter properties. Model update handling
* can be done via Binding.
*/ */
class CreateOfferPresenter class CreateOfferPresenter {
{
private static final Logger log = LoggerFactory.getLogger(CreateOfferPresenter.class); private static final Logger log = LoggerFactory.getLogger(CreateOfferPresenter.class);
private CreateOfferModel model; private CreateOfferModel model;
@ -83,8 +84,7 @@ class CreateOfferPresenter
// Constructor // Constructor
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
CreateOfferPresenter(CreateOfferModel model) CreateOfferPresenter(CreateOfferModel model) {
{
this.model = model; this.model = model;
} }
@ -93,35 +93,35 @@ class CreateOfferPresenter
// Lifecycle // Lifecycle
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
void onViewInitialized() void onViewInitialized() {
{
totalFeesLabel.set(BSFormatter.formatBtc(model.totalFeesAsCoin)); totalFeesLabel.set(BSFormatter.formatBtc(model.totalFeesAsCoin));
paymentLabel.set("Bitsquare trade (" + model.getOfferId() + ")"); paymentLabel.set("Bitsquare trade (" + model.getOfferId() + ")");
// address.set(model.addressEntry.getAddress().toString()); // address.set(model.addressEntry.getAddress().toString());
setupInputListeners(); setupInputListeners();
collateralLabel.bind(Bindings.createStringBinding(() -> "Collateral (" + BSFormatter.formatCollateralPercent(model.collateralAsLong.get()) + "):", model.collateralAsLong)); collateralLabel.bind(Bindings.createStringBinding(() -> "Collateral (" + BSFormatter.formatCollateralPercent
bankAccountType.bind(Bindings.createStringBinding(() -> Localisation.get(model.bankAccountType.get()), model.bankAccountType)); (model.collateralAsLong.get()) + "):", model.collateralAsLong));
bankAccountType.bind(Bindings.createStringBinding(() -> Localisation.get(model.bankAccountType.get()),
model.bankAccountType));
bankAccountCurrency.bind(model.bankAccountCurrency); bankAccountCurrency.bind(model.bankAccountCurrency);
bankAccountCounty.bind(model.bankAccountCounty); bankAccountCounty.bind(model.bankAccountCounty);
totalToPayAsCoin.bind(model.totalToPayAsCoin); totalToPayAsCoin.bind(model.totalToPayAsCoin);
model.acceptedCountries.addListener((Observable o) -> acceptedCountries.set(BSFormatter.countryLocalesToString(model.acceptedCountries))); model.acceptedCountries.addListener((Observable o) -> acceptedCountries.set(BSFormatter
model.acceptedLanguages.addListener((Observable o) -> acceptedLanguages.set(BSFormatter.languageLocalesToString(model.acceptedLanguages))); .countryLocalesToString(model.acceptedCountries)));
model.acceptedLanguages.addListener((Observable o) -> acceptedLanguages.set(BSFormatter
.languageLocalesToString(model.acceptedLanguages)));
} }
void deactivate() void deactivate() {
{
} }
void activate() void activate() {
{
model.activate(); model.activate();
// totalToPay.addListener((ov) -> addressTextField.setAmountToPay(model.totalToPayAsCoin)); // totalToPay.addListener((ov) -> addressTextField.setAmountToPay(model.totalToPayAsCoin));
} }
@ -130,8 +130,7 @@ class CreateOfferPresenter
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
void setOrderBookFilter(OrderBookFilter orderBookFilter) void setOrderBookFilter(OrderBookFilter orderBookFilter) {
{
// model // model
model.setDirection(orderBookFilter.getDirection()); model.setDirection(orderBookFilter.getDirection());
model.amountAsCoin = orderBookFilter.getAmount(); model.amountAsCoin = orderBookFilter.getAmount();
@ -151,8 +150,7 @@ class CreateOfferPresenter
// View Events // View Events
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
void placeOffer() void placeOffer() {
{
model.amountAsCoin = parseToCoin(amount.get()); model.amountAsCoin = parseToCoin(amount.get());
model.minAmountAsCoin = parseToCoin(minAmount.get()); model.minAmountAsCoin = parseToCoin(minAmount.get());
model.priceAsFiat = parseToFiat(price.get()); model.priceAsFiat = parseToFiat(price.get());
@ -162,8 +160,7 @@ class CreateOfferPresenter
//balanceTextField.getBalance() //balanceTextField.getBalance()
if (inputValid()) if (inputValid()) {
{
model.placeOffer(); model.placeOffer();
isPlaceOfferButtonDisabled.set(true); isPlaceOfferButtonDisabled.set(true);
placeOfferButtonVisible.set(true); placeOfferButtonVisible.set(true);
@ -183,8 +180,7 @@ class CreateOfferPresenter
} }
void close() void close() {
{
} }
@ -192,14 +188,12 @@ class CreateOfferPresenter
// //
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private boolean inputValid() private boolean inputValid() {
{
//TODO //TODO
return true; return true;
} }
void setupInputListeners() void setupInputListeners() {
{
// bindBidirectional for amount, price, volume and minAmount // bindBidirectional for amount, price, volume and minAmount
amount.addListener(ov -> { amount.addListener(ov -> {
@ -225,25 +219,21 @@ class CreateOfferPresenter
} }
private void setVolume() private void setVolume() {
{
model.amountAsCoin = parseToCoin(amount.get()); model.amountAsCoin = parseToCoin(amount.get());
model.priceAsFiat = parseToFiat(price.get()); model.priceAsFiat = parseToFiat(price.get());
if (model.priceAsFiat != null && model.amountAsCoin != null && !model.amountAsCoin.isZero()) if (model.priceAsFiat != null && model.amountAsCoin != null && !model.amountAsCoin.isZero()) {
{
model.tradeVolumeAsFiat = new ExchangeRate(model.priceAsFiat).coinToFiat(model.amountAsCoin); model.tradeVolumeAsFiat = new ExchangeRate(model.priceAsFiat).coinToFiat(model.amountAsCoin);
volume.set(formatFiat(model.tradeVolumeAsFiat)); volume.set(formatFiat(model.tradeVolumeAsFiat));
} }
} }
private void setAmount() private void setAmount() {
{
model.tradeVolumeAsFiat = parseToFiat(volume.get()); model.tradeVolumeAsFiat = parseToFiat(volume.get());
model.priceAsFiat = parseToFiat(price.get()); model.priceAsFiat = parseToFiat(price.get());
if (model.tradeVolumeAsFiat != null && model.priceAsFiat != null && !model.priceAsFiat.isZero()) if (model.tradeVolumeAsFiat != null && model.priceAsFiat != null && !model.priceAsFiat.isZero()) {
{
model.amountAsCoin = new ExchangeRate(model.priceAsFiat).fiatToCoin(model.tradeVolumeAsFiat); model.amountAsCoin = new ExchangeRate(model.priceAsFiat).fiatToCoin(model.tradeVolumeAsFiat);
// If we got a btc value with more then 4 decimals we convert it to max 4 decimals // If we got a btc value with more then 4 decimals we convert it to max 4 decimals
@ -254,31 +244,26 @@ class CreateOfferPresenter
} }
} }
private void setTotalToPay() private void setTotalToPay() {
{
setCollateral(); setCollateral();
if (model.collateralAsCoin != null) if (model.collateralAsCoin != null) {
{
model.totalToPayAsCoin.set(model.collateralAsCoin.add(model.totalFeesAsCoin)); model.totalToPayAsCoin.set(model.collateralAsCoin.add(model.totalFeesAsCoin));
totalToPay.bind(createStringBinding(() -> formatBtcWithCode(model.totalToPayAsCoin.get()), model.totalToPayAsCoin)); totalToPay.bind(createStringBinding(() -> formatBtcWithCode(model.totalToPayAsCoin.get()),
model.totalToPayAsCoin));
} }
} }
private void setCollateral() private void setCollateral() {
{ if (model.amountAsCoin != null) {
if (model.amountAsCoin != null)
{
model.collateralAsCoin = model.amountAsCoin.multiply(model.collateralAsLong.get()).divide(1000); model.collateralAsCoin = model.amountAsCoin.multiply(model.collateralAsLong.get()).divide(1000);
collateral.set(BSFormatter.formatBtcWithCode(model.collateralAsCoin)); collateral.set(BSFormatter.formatBtcWithCode(model.collateralAsCoin));
} }
} }
// We adjust the volume if fractional coins result from volume/price division on focus out // We adjust the volume if fractional coins result from volume/price division on focus out
void checkVolumeOnFocusOut(Boolean oldValue, Boolean newValue, String volumeTextFieldText) void checkVolumeOnFocusOut(Boolean oldValue, Boolean newValue, String volumeTextFieldText) {
{ if (oldValue && !newValue) {
if (oldValue && !newValue)
{
setVolume(); setVolume();
if (!formatFiat(parseToFiat(volumeTextFieldText)).equals(volume.get())) if (!formatFiat(parseToFiat(volumeTextFieldText)).equals(volume.get()))
showVolumeAdjustedWarning.set(true); showVolumeAdjustedWarning.set(true);
@ -291,15 +276,13 @@ class CreateOfferPresenter
amountTextField.reValidate();*/ amountTextField.reValidate();*/
} }
void onFocusOutAmountTextField(Boolean oldValue, Boolean newValue) void onFocusOutAmountTextField(Boolean oldValue, Boolean newValue) {
{
// only on focus out and ignore focus loss from window // only on focus out and ignore focus loss from window
/* if (!newValue && amountTextField.getScene() != null && amountTextField.getScene().getWindow().isFocused()) /* if (!newValue && amountTextField.getScene() != null && amountTextField.getScene().getWindow().isFocused())
volumeTextField.reValidate();*/ volumeTextField.reValidate();*/
} }
void onFocusOutPriceTextField(Boolean oldValue, Boolean newValue) void onFocusOutPriceTextField(Boolean oldValue, Boolean newValue) {
{
// only on focus out and ignore focus loss from window // only on focus out and ignore focus loss from window
/* if (!newValue && priceTextField.getScene() != null && priceTextField.getScene().getWindow().isFocused()) /* if (!newValue && priceTextField.getScene() != null && priceTextField.getScene().getWindow().isFocused())
volumeTextField.reValidate();*/ volumeTextField.reValidate();*/

View file

@ -20,11 +20,11 @@
<?import io.bitsquare.gui.components.btc.AddressTextField?> <?import io.bitsquare.gui.components.btc.AddressTextField?>
<?import io.bitsquare.gui.components.btc.BalanceTextField?> <?import io.bitsquare.gui.components.btc.BalanceTextField?>
<?import io.bitsquare.gui.components.confidence.ConfidenceProgressIndicator?> <?import io.bitsquare.gui.components.confidence.ConfidenceProgressIndicator?>
<?import io.bitsquare.gui.components.*?> <?import io.bitsquare.gui.components.ValidatingTextField?>
<?import javafx.geometry.*?> <?import io.bitsquare.gui.components.VSpacer?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.trade.createoffer.CreateOfferCodeBehind" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.trade.createoffer.CreateOfferCodeBehind"
prefHeight="500" prefWidth="800" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="10.0" prefHeight="500" prefWidth="800" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="10.0"
AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0" AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0"

View file

@ -261,8 +261,8 @@ public class OrderBookController extends CachedViewController {
} }
else { else {
Action response = Popups.openErrorPopup("Registration fee not confirmed yet", Action response = Popups.openErrorPopup("Registration fee not confirmed yet",
"The registration fee transaction has not been confirmed yet in the blockchain. " + "The registration fee transaction has not been confirmed yet in the blockchain. " +
"Please wait until it has at least 1 confirmation."); "Please wait until it has at least 1 confirmation.");
if (response == Dialog.Actions.OK) { if (response == Dialog.Actions.OK) {
MainController.GET_INSTANCE().loadViewAndGetChildController(NavigationItem.FUNDS); MainController.GET_INSTANCE().loadViewAndGetChildController(NavigationItem.FUNDS);
} }
@ -270,8 +270,8 @@ public class OrderBookController extends CachedViewController {
} }
else { else {
Action response = Popups.openErrorPopup("Missing registration fee", Action response = Popups.openErrorPopup("Missing registration fee",
"You have not funded the full registration fee of " + BSFormatter "You have not funded the full registration fee of " + BSFormatter
.formatCoinWithCode(FeePolicy.ACCOUNT_REGISTRATION_FEE) + " BTC."); .formatCoinWithCode(FeePolicy.ACCOUNT_REGISTRATION_FEE) + " BTC.");
if (response == Dialog.Actions.OK) { if (response == Dialog.Actions.OK) {
MainController.GET_INSTANCE().loadViewAndGetChildController(NavigationItem.FUNDS); MainController.GET_INSTANCE().loadViewAndGetChildController(NavigationItem.FUNDS);
} }
@ -287,21 +287,21 @@ public class OrderBookController extends CachedViewController {
if (selectedIndex >= 0) { if (selectedIndex >= 0) {
Dialogs.CommandLink settingsCommandLink = new Dialogs.CommandLink("Open settings", Dialogs.CommandLink settingsCommandLink = new Dialogs.CommandLink("Open settings",
"You need to configure your settings before you can actively trade."); "You need to configure your settings before you can actively trade.");
Dialogs.CommandLink depositFeeCommandLink = new Dialogs.CommandLink("Deposit funds", 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" + "You need to pay the registration fee before you can actively trade. That is needed as prevention" +
" against fraud."); " against fraud.");
Dialogs.CommandLink sendRegistrationCommandLink = new Dialogs.CommandLink("Publish registration", Dialogs.CommandLink sendRegistrationCommandLink = new Dialogs.CommandLink("Publish registration",
"When settings are configured and the fee deposit is done your registration transaction will be " + "When settings are configured and the fee deposit is done your registration transaction will be " +
"published to " "published to "
+ "the Bitcoin \nnetwork."); + "the Bitcoin \nnetwork.");
List<Dialogs.CommandLink> commandLinks = Arrays.asList(settingsCommandLink, depositFeeCommandLink, List<Dialogs.CommandLink> commandLinks = Arrays.asList(settingsCommandLink, depositFeeCommandLink,
sendRegistrationCommandLink); sendRegistrationCommandLink);
Action registrationMissingAction = Popups.openRegistrationMissingPopup("Not registered yet", Action registrationMissingAction = Popups.openRegistrationMissingPopup("Not registered yet",
"Please follow these steps:", "Please follow these steps:",
"You need to register before you can place an offer.", "You need to register before you can place an offer.",
commandLinks, commandLinks,
selectedIndex); selectedIndex);
if (registrationMissingAction == settingsCommandLink) { if (registrationMissingAction == settingsCommandLink) {
MainController.GET_INSTANCE().loadViewAndGetChildController(NavigationItem.SETTINGS); MainController.GET_INSTANCE().loadViewAndGetChildController(NavigationItem.SETTINGS);
} }
@ -371,7 +371,7 @@ public class OrderBookController extends CachedViewController {
orderBook.applyFilter(orderBookFilter); orderBook.applyFilter(orderBookFilter);
priceColumn.setSortType((orderBookFilter.getDirection() == Direction.BUY) ? priceColumn.setSortType((orderBookFilter.getDirection() == Direction.BUY) ?
TableColumn.SortType.ASCENDING : TableColumn.SortType.DESCENDING); TableColumn.SortType.ASCENDING : TableColumn.SortType.DESCENDING);
orderBookTable.sort(); orderBookTable.sort();
if (orderBookTable.getItems() != null) { if (orderBookTable.getItems() != null) {
@ -487,8 +487,8 @@ public class OrderBookController extends CachedViewController {
} catch (Exception e) { } catch (Exception e) {
log.warn("Country icon not found: /images/countries/" + log.warn("Country icon not found: /images/countries/" +
country.getCode().toLowerCase() + ".png country name: " + country.getCode().toLowerCase() + ".png country name: " +
country.getName()); country.getName());
} }
Tooltip.install(this, new Tooltip(country.getName())); Tooltip.install(this, new Tooltip(country.getName()));
} }

View file

@ -17,11 +17,10 @@
~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. ~ along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
--> -->
<?import javafx.geometry.*?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.PropertyValueFactory?> <?import javafx.scene.control.cell.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.trade.orderbook.OrderBookController" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.trade.orderbook.OrderBookController"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0" AnchorPane.topAnchor="0.0"

View file

@ -21,7 +21,6 @@
<?import javafx.geometry.Insets?> <?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.trade.takeoffer.TakerOfferController" <AnchorPane fx:id="root" fx:controller="io.bitsquare.gui.trade.takeoffer.TakerOfferController"
xmlns:fx="http://javafx.com/fxml"> xmlns:fx="http://javafx.com/fxml">
<Accordion fx:id="accordion" AnchorPane.bottomAnchor="30.0" AnchorPane.leftAnchor="10.0" <Accordion fx:id="accordion" AnchorPane.bottomAnchor="30.0" AnchorPane.leftAnchor="10.0"

View file

@ -168,7 +168,7 @@ public class TakerOfferController extends CachedViewController {
} }
else if (tradeManager.isOfferAlreadyInTrades(offer)) { else if (tradeManager.isOfferAlreadyInTrades(offer)) {
Popups.openErrorPopup("Offer previously accepted", Popups.openErrorPopup("Offer previously accepted",
"You have that offer already taken. Open the offer section to find that trade."); "You have that offer already taken. Open the offer section to find that trade.");
} }
else { else {
takeOfferButton.setDisable(true); takeOfferButton.setDisable(true);
@ -179,8 +179,8 @@ public class TakerOfferController extends CachedViewController {
setDepositTxId(depositTxId); setDepositTxId(depositTxId);
accordion.setExpandedPane(waitBankTxTitledPane); accordion.setExpandedPane(waitBankTxTitledPane);
infoLabel.setText("Deposit transaction published by offerer.\n" + infoLabel.setText("Deposit transaction published by offerer.\n" +
"As soon as the offerer starts the \n" + "As soon as the offerer starts the \n" +
"Bank transfer, you will get informed."); "Bank transfer, you will get informed.");
depositTxIdTextField.setText(depositTxId); depositTxIdTextField.setText(depositTxId);
} }
@ -210,7 +210,7 @@ public class TakerOfferController extends CachedViewController {
public void onFault(Throwable throwable, ProtocolForTakerAsSeller.State state) { public void onFault(Throwable throwable, ProtocolForTakerAsSeller.State state) {
log.error("Error while executing trade process at state: " + state + " / " + throwable); log.error("Error while executing trade process at state: " + state + " / " + throwable);
Popups.openErrorPopup("Error while executing trade process", Popups.openErrorPopup("Error while executing trade process",
"Error while executing trade process at state: " + state + " / " + throwable); "Error while executing trade process at state: " + state + " / " + throwable);
} }
@Override @Override
@ -227,8 +227,8 @@ public class TakerOfferController extends CachedViewController {
public void onTakeOfferRequestRejected(Trade trade) { public void onTakeOfferRequestRejected(Trade trade) {
log.error("Take offer request rejected"); log.error("Take offer request rejected");
Popups.openErrorPopup("Take offer request rejected", Popups.openErrorPopup("Take offer request rejected",
"Your take offer request has been rejected. It might be that the offerer got another " + "Your take offer request has been rejected. It might be that the offerer got another " +
"request shortly before your request arrived."); "request shortly before your request arrived.");
} }
}); });
} }

View file

@ -40,36 +40,32 @@ import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.*; import static com.google.common.base.Preconditions.*;
//TODO a lot of old trash... need to cleanup... //TODO a lot of old trash... need to cleanup...
public class BSFormatter public class BSFormatter {
{
private static final Logger log = LoggerFactory.getLogger(BSFormatter.class); private static final Logger log = LoggerFactory.getLogger(BSFormatter.class);
// format is like: 1,00 or 1,0010 never more then 4 decimals // format is like: 1,00 or 1,0010 never more then 4 decimals
private static CoinFormat coinFormat = CoinFormat.BTC.repeatOptionalDecimals(2, 1); private static CoinFormat coinFormat = CoinFormat.BTC.repeatOptionalDecimals(2, 1);
// format is like: 1,00 never more then 2 decimals // format is like: 1,00 never more then 2 decimals
private static CoinFormat fiatFormat = CoinFormat.FIAT.repeatOptionalDecimals(0, 0); private static CoinFormat fiatFormat = CoinFormat.FIAT.repeatOptionalDecimals(0, 0);
private static String currencyCode = Currency.getInstance(Locale.getDefault()).getCurrencyCode(); private static String currencyCode = Currency.getInstance(Locale.getDefault()).getCurrencyCode();
private static Locale locale = Locale.getDefault(); private static Locale locale = Locale.getDefault();
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Config // Config
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static void useMilliBitFormat() public static void useMilliBitFormat() {
{
coinFormat = CoinFormat.MBTC.repeatOptionalDecimals(2, 1); coinFormat = CoinFormat.MBTC.repeatOptionalDecimals(2, 1);
} }
public static void setFiatCurrencyCode(String currencyCode) public static void setFiatCurrencyCode(String currencyCode) {
{
BSFormatter.currencyCode = currencyCode; BSFormatter.currencyCode = currencyCode;
} }
public static void setLocale(Locale locale) public static void setLocale(Locale locale) {
{
BSFormatter.locale = locale; BSFormatter.locale = locale;
} }
@ -78,39 +74,30 @@ public class BSFormatter
// BTC // BTC
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static String formatBtc(Coin coin) public static String formatBtc(Coin coin) {
{ try {
try
{
return coinFormat.noCode().format(coin).toString(); return coinFormat.noCode().format(coin).toString();
} catch (Throwable t) } catch (Throwable t) {
{
log.warn("Exception at formatBtc: " + t.toString()); log.warn("Exception at formatBtc: " + t.toString());
return ""; return "";
} }
} }
public static String formatBtcWithCode(Coin coin) public static String formatBtcWithCode(Coin coin) {
{ try {
try
{
return coinFormat.postfixCode().format(coin).toString(); return coinFormat.postfixCode().format(coin).toString();
} catch (Throwable t) } catch (Throwable t) {
{
log.warn("Exception at formatBtcWithCode: " + t.toString()); log.warn("Exception at formatBtcWithCode: " + t.toString());
return ""; return "";
} }
} }
public static Coin parseToCoin(String input) public static Coin parseToCoin(String input) {
{ try {
try
{
input = input.replace(",", "."); input = input.replace(",", ".");
Double.parseDouble(input); // test if valid double Double.parseDouble(input); // test if valid double
return Coin.parseCoin(input); return Coin.parseCoin(input);
} catch (Throwable t) } catch (Throwable t) {
{
log.warn("Exception at parseToCoin: " + t.toString()); log.warn("Exception at parseToCoin: " + t.toString());
return Coin.ZERO; return Coin.ZERO;
} }
@ -122,8 +109,7 @@ public class BSFormatter
* @param coin The coin which should be transformed * @param coin The coin which should be transformed
* @return The transformed coin * @return The transformed coin
*/ */
public static Coin applyFormatRules(Coin coin) public static Coin applyFormatRules(Coin coin) {
{
return parseToCoin(formatBtc(coin)); return parseToCoin(formatBtc(coin));
} }
@ -132,39 +118,30 @@ public class BSFormatter
// FIAT // FIAT
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public static String formatFiat(Fiat fiat) public static String formatFiat(Fiat fiat) {
{ try {
try
{
return fiatFormat.noCode().format(fiat).toString(); return fiatFormat.noCode().format(fiat).toString();
} catch (Throwable t) } catch (Throwable t) {
{
log.warn("Exception at formatFiat: " + t.toString()); log.warn("Exception at formatFiat: " + t.toString());
return ""; return "";
} }
} }
public static String formatFiatWithCode(Fiat fiat) public static String formatFiatWithCode(Fiat fiat) {
{ try {
try
{
return fiatFormat.postfixCode().format(fiat).toString(); return fiatFormat.postfixCode().format(fiat).toString();
} catch (Throwable t) } catch (Throwable t) {
{
log.warn("Exception at formatFiatWithCode: " + t.toString()); log.warn("Exception at formatFiatWithCode: " + t.toString());
return ""; return "";
} }
} }
public static Fiat parseToFiat(String input) public static Fiat parseToFiat(String input) {
{ try {
try
{
input = input.replace(",", "."); input = input.replace(",", ".");
Double.parseDouble(input); // test if valid double Double.parseDouble(input); // test if valid double
return Fiat.parseFiat(currencyCode, input); return Fiat.parseFiat(currencyCode, input);
} catch (Exception e) } catch (Exception e) {
{
return Fiat.valueOf(currencyCode, 0); return Fiat.valueOf(currencyCode, 0);
} }
} }
@ -175,46 +152,39 @@ public class BSFormatter
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
/** /**
* @param input String to be converted to a double. Both decimal points "." and "," are supported. Thousands separator is not supported. * @param input String to be converted to a double. Both decimal points "." and ",
* " are supported. Thousands separator is not supported.
* @return Returns a double value. Any invalid value returns Double.NEGATIVE_INFINITY. * @return Returns a double value. Any invalid value returns Double.NEGATIVE_INFINITY.
*/ */
public static double parseToDouble(String input) public static double parseToDouble(String input) {
{ try {
try
{
checkNotNull(input); checkNotNull(input);
checkArgument(input.length() > 0); checkArgument(input.length() > 0);
input = input.replace(",", ".").trim(); input = input.replace(",", ".").trim();
return Double.parseDouble(input); return Double.parseDouble(input);
} catch (Exception e) } catch (Exception e) {
{
return 0; return 0;
} }
} }
public static String formatDirection(Direction direction, boolean allUpperCase) public static String formatDirection(Direction direction, boolean allUpperCase) {
{
String result = (direction == Direction.BUY) ? "Buy" : "Sell"; String result = (direction == Direction.BUY) ? "Buy" : "Sell";
if (allUpperCase) if (allUpperCase) {
{
result = result.toUpperCase(); result = result.toUpperCase();
} }
return result; return result;
} }
public static String formatDouble(double value) public static String formatDouble(double value) {
{
return formatDouble(value, 4); return formatDouble(value, 4);
} }
public static String formatDouble(double value, int fractionDigits) public static String formatDouble(double value, int fractionDigits) {
{
DecimalFormat decimalFormat = getDecimalFormat(fractionDigits); DecimalFormat decimalFormat = getDecimalFormat(fractionDigits);
return decimalFormat.format(value); return decimalFormat.format(value);
} }
public static DecimalFormat getDecimalFormat(int fractionDigits) public static DecimalFormat getDecimalFormat(int fractionDigits) {
{
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale); DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMinimumFractionDigits(fractionDigits); decimalFormat.setMinimumFractionDigits(fractionDigits);
decimalFormat.setMaximumFractionDigits(fractionDigits); decimalFormat.setMaximumFractionDigits(fractionDigits);
@ -222,32 +192,26 @@ public class BSFormatter
return decimalFormat; return decimalFormat;
} }
public static String countryLocalesToString(List<Country> countries) public static String countryLocalesToString(List<Country> countries) {
{
String result = ""; String result = "";
int i = 0; int i = 0;
for (Country country : countries) for (Country country : countries) {
{
result += country.getName(); result += country.getName();
i++; i++;
if (i < countries.size()) if (i < countries.size()) {
{
result += ", "; result += ", ";
} }
} }
return result; return result;
} }
public static String languageLocalesToString(List<Locale> languageLocales) public static String languageLocalesToString(List<Locale> languageLocales) {
{
String result = ""; String result = "";
int i = 0; int i = 0;
for (Locale locale : languageLocales) for (Locale locale : languageLocales) {
{
result += locale.getDisplayLanguage(); result += locale.getDisplayLanguage();
i++; i++;
if (i < languageLocales.size()) if (i < languageLocales.size()) {
{
result += ", "; result += ", ";
} }
} }
@ -255,16 +219,13 @@ public class BSFormatter
} }
public static String arbitrationMethodsToString(List<Arbitrator.METHOD> items) public static String arbitrationMethodsToString(List<Arbitrator.METHOD> items) {
{
String result = ""; String result = "";
int i = 0; int i = 0;
for (Arbitrator.METHOD item : items) for (Arbitrator.METHOD item : items) {
{
result += Localisation.get(item.toString()); result += Localisation.get(item.toString());
i++; i++;
if (i < items.size()) if (i < items.size()) {
{
result += ", "; result += ", ";
} }
} }
@ -272,62 +233,52 @@ public class BSFormatter
} }
public static String arbitrationIDVerificationsToString(List<Arbitrator.ID_VERIFICATION> items) public static String arbitrationIDVerificationsToString(List<Arbitrator.ID_VERIFICATION> items) {
{
String result = ""; String result = "";
int i = 0; int i = 0;
for (Arbitrator.ID_VERIFICATION item : items) for (Arbitrator.ID_VERIFICATION item : items) {
{
result += Localisation.get(item.toString()); result += Localisation.get(item.toString());
i++; i++;
if (i < items.size()) if (i < items.size()) {
{
result += ", "; result += ", ";
} }
} }
return result; return result;
} }
public static String formatDateTime(Date date) public static String formatDateTime(Date date) {
{
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale); DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
return dateFormatter.format(date) + " " + timeFormatter.format(date); return dateFormatter.format(date) + " " + timeFormatter.format(date);
} }
public static String formatCollateralPercent(long collateral) public static String formatCollateralPercent(long collateral) {
{
return getDecimalFormat(1).format(collateral / 10) + " %"; return getDecimalFormat(1).format(collateral / 10) + " %";
} }
@Deprecated @Deprecated
public static String formatPrice(double volume) public static String formatPrice(double volume) {
{
return formatDouble(volume); return formatDouble(volume);
} }
@Deprecated @Deprecated
public static String formatVolume(double volume) public static String formatVolume(double volume) {
{
return formatDouble(volume); return formatDouble(volume);
} }
@Deprecated @Deprecated
public static String formatVolumeWithMinVolume(double volume, double minVolume) public static String formatVolumeWithMinVolume(double volume, double minVolume) {
{
return formatDouble(volume) + " (" + formatDouble(minVolume) + ")"; return formatDouble(volume) + " (" + formatDouble(minVolume) + ")";
} }
@Deprecated @Deprecated
public static String formatCoin(Coin coin) public static String formatCoin(Coin coin) {
{
return coin != null ? coin.toPlainString() : ""; return coin != null ? coin.toPlainString() : "";
} }
@Deprecated @Deprecated
public static String formatCoinWithCode(Coin coin) public static String formatCoinWithCode(Coin coin) {
{
return coin != null ? coin.toFriendlyString() : ""; return coin != null ? coin.toFriendlyString() : "";
} }
} }

View file

@ -26,7 +26,7 @@ import org.slf4j.LoggerFactory;
/** /**
* BtcValidator for validating BTC values. * BtcValidator for validating BTC values.
* <p/> * <p>
* That class implements just what we need for the moment. It is not intended as a general purpose library class. * That class implements just what we need for the moment. It is not intended as a general purpose library class.
*/ */
public class BtcValidator extends NumberValidator { public class BtcValidator extends NumberValidator {

View file

@ -22,7 +22,7 @@ import org.slf4j.LoggerFactory;
/** /**
* FiatNumberValidator for validating fiat values. * FiatNumberValidator for validating fiat values.
* <p/> * <p>
* That class implements just what we need for the moment. It is not intended as a general purpose library class. * That class implements just what we need for the moment. It is not intended as a general purpose library class.
*/ */
public class FiatValidator extends NumberValidator { public class FiatValidator extends NumberValidator {

View file

@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory;
* Localisation not supported at the moment * Localisation not supported at the moment
* The decimal mark can be either "." or ",". Thousand separators are not supported yet, * The decimal mark can be either "." or ",". Thousand separators are not supported yet,
* but might be added alter with Local support. * but might be added alter with Local support.
* <p/> * <p>
* That class implements just what we need for the moment. It is not intended as a general purpose library class. * That class implements just what we need for the moment. It is not intended as a general purpose library class.
*/ */
public abstract class NumberValidator { public abstract class NumberValidator {

View file

@ -46,7 +46,7 @@ public class Localisation {
public static String get(String key) { public static String get(String key) {
if (key == null) if (key == null)
return ""; return "";
try { try {
return Localisation.getResourceBundle().getString(key); return Localisation.getResourceBundle().getString(key);
} catch (MissingResourceException e) { } catch (MissingResourceException e) {

View file

@ -67,7 +67,7 @@ import org.slf4j.LoggerFactory;
* It is the translating domain specific functionality to the messaging layer. * It is the translating domain specific functionality to the messaging layer.
* The TomP2P library codebase shall not be used outside that facade. * The TomP2P library codebase shall not be used outside that facade.
* That way we limit the dependency of the TomP2P library only to that class (and it's sub components). * That way we limit the dependency of the TomP2P library only to that class (and it's sub components).
* <p/> * <p>
* TODO: improve callbacks that Platform.runLater is not necessary. We call usually that methods form teh UI thread. * TODO: improve callbacks that Platform.runLater is not necessary. We call usually that methods form teh UI thread.
*/ */
public class MessageFacade implements MessageBroker { public class MessageFacade implements MessageBroker {

View file

@ -50,9 +50,9 @@ import static io.bitsquare.util.Validator.*;
/** /**
* Responsible for the correct execution of the sequence of tasks, message passing to the peer and message processing * Responsible for the correct execution of the sequence of tasks, message passing to the peer and message processing
* from the peer. * from the peer.
* <p/> * <p>
* This class handles the role of the offerer as the Bitcoin buyer. * This class handles the role of the offerer as the Bitcoin buyer.
* <p/> * <p>
* It uses sub tasks to not pollute the main class too much with all the async result/fault handling. * It uses sub tasks to not pollute the main class too much with all the async result/fault handling.
* Any data from incoming messages need to be validated before further processing. * Any data from incoming messages need to be validated before further processing.
*/ */

View file

@ -33,13 +33,11 @@ import org.slf4j.LoggerFactory;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class CreateOfferPresenterTest public class CreateOfferPresenterTest {
{
private static final Logger log = LoggerFactory.getLogger(CreateOfferPresenterTest.class); private static final Logger log = LoggerFactory.getLogger(CreateOfferPresenterTest.class);
@Test @Test
public void testBindings() public void testBindings() {
{
CreateOfferModel model = new CreateOfferModel(null, null, null, null); CreateOfferModel model = new CreateOfferModel(null, null, null, null);
BSFormatter.setLocale(Locale.US); BSFormatter.setLocale(Locale.US);
@ -54,7 +52,7 @@ public class CreateOfferPresenterTest
assertEquals(Coin.COIN, model.amountAsCoin); assertEquals(Coin.COIN, model.amountAsCoin);
assertEquals(Fiat.valueOf("EUR", 500 * 10000), model.priceAsFiat); assertEquals(Fiat.valueOf("EUR", 500 * 10000), model.priceAsFiat);
assertEquals(Fiat.valueOf("EUR", 500 * 10000), model.tradeVolumeAsFiat); assertEquals(Fiat.valueOf("EUR", 500 * 10000), model.tradeVolumeAsFiat);
assertEquals(Coin.parseCoin("0.1011"), model.totalToPayAsCoin); assertEquals(Coin.parseCoin("0.1011"), model.totalToPayAsCoin.get());
presenter.price.set("500"); presenter.price.set("500");
presenter.volume.set("500"); presenter.volume.set("500");