Adjust line wrapping by hand

This commit is contained in:
Chris Beams 2014-08-26 10:10:59 +02:00
parent 1ad1d318e8
commit a3c4df8dc3
No known key found for this signature in database
GPG key ID: 3D214F8F5BC5ED73
59 changed files with 805 additions and 805 deletions

View file

@ -82,8 +82,8 @@ public class BitSquare extends Application {
Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> Popups.handleUncaughtExceptions Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> Popups.handleUncaughtExceptions
(Throwables.getRootCause(throwable))); (Throwables.getRootCause(throwable)));
StorageDirectory.setStorageDirectory(new File(StorageDirectory.getApplicationDirectory().getCanonicalPath() + StorageDirectory.setStorageDirectory(
"/data")); new File(StorageDirectory.getApplicationDirectory().getCanonicalPath() + "/data"));
// currently there is not SystemTray support for java fx (planned for version 3) so we use the old AWT // currently there is not SystemTray support for java fx (planned for version 3) so we use the old AWT
AWTSystemTray.createSystemTray(primaryStage); AWTSystemTray.createSystemTray(primaryStage);
@ -110,8 +110,8 @@ public class BitSquare extends Application {
GuiceFXMLLoader.setInjector(injector); GuiceFXMLLoader.setInjector(injector);
final GuiceFXMLLoader loader = new GuiceFXMLLoader(getClass().getResource(NavigationItem.MAIN.getFxmlUrl()), final GuiceFXMLLoader loader =
false); new GuiceFXMLLoader(getClass().getResource(NavigationItem.MAIN.getFxmlUrl()), false);
final Parent view = loader.load(); final Parent view = loader.load();
final Scene scene = new Scene(view, 1000, 750); final Scene scene = new Scene(view, 1000, 750);
scene.getStylesheets().setAll(getClass().getResource("/io/bitsquare/gui/bitsquare.css").toExternalForm()); scene.getStylesheets().setAll(getClass().getResource("/io/bitsquare/gui/bitsquare.css").toExternalForm());

View file

@ -42,8 +42,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 {
private static final Logger log = LoggerFactory.getLogger(SeedNode.class); private static final Logger log = LoggerFactory.getLogger(SeedNode.class);
@ -109,8 +108,8 @@ public class SeedNode extends Thread {
public Peer startupPeer() { public Peer startupPeer() {
Peer peer = null; Peer peer = null;
try { try {
peer = new PeerBuilder(Number160.createHash(seedNodeAddress.getId())).ports(seedNodeAddress.getPort()) peer = new PeerBuilder(
.start(); Number160.createHash(seedNodeAddress.getId())).ports(seedNodeAddress.getPort()).start();
// Need to add all features the clients will use (otherwise msg type is UNKNOWN_ID) // Need to add all features the clients will use (otherwise msg type is UNKNOWN_ID)
new PeerBuilderDHT(peer).start(); new PeerBuilderDHT(peer).start();

View file

@ -171,7 +171,7 @@ public class AddressBasedCoinSelector extends DefaultCoinSelector {
confidence.getSource().equals(TransactionConfidence.Source.SELF) && confidence.getSource().equals(TransactionConfidence.Source.SELF) &&
// In regtest mode we expect to have only one peer, so we won't see transactions propagate. // In regtest mode we expect to have only one peer, so we won't see transactions propagate.
// TODO: The value 1 below dates from a time when transactions we broadcast *to* were // TODO: The value 1 below dates from a time when transactions we broadcast *to* were
counted, set to 0 // counted, set to 0
(confidence.numBroadcastPeers() > 1 || tx.getParams() == RegTestParams.get()); (confidence.numBroadcastPeers() > 1 || tx.getParams() == RegTestParams.get());
} }
*/ */

View file

@ -41,8 +41,8 @@ public class FeePolicy {
this.params = params; this.params = params;
} }
//TODO other users or dev address? use donation option list? (dev, other users, wikileaks, tor, //TODO other users or dev address? use donation option list?
// sub projects (bitcoinj, tomp2p,...)...) // (dev, other users, wikileaks, tor, sub projects (bitcoinj, tomp2p,...)...)
public Address getAddressForRegistrationFee() { public Address getAddressForRegistrationFee() {
try { try {

View file

@ -200,8 +200,8 @@ public class WalletFacade {
List<AddressEntry> persistedAddressEntryList = (List<AddressEntry>) serializable; List<AddressEntry> persistedAddressEntryList = (List<AddressEntry>) serializable;
if (serializable instanceof List) { if (serializable instanceof List) {
for (AddressEntry persistedAddressEntry : persistedAddressEntryList) { for (AddressEntry persistedAddressEntry : persistedAddressEntryList) {
persistedAddressEntry.setDeterministicKey((DeterministicKey) wallet.findKeyFromPubHash persistedAddressEntry.setDeterministicKey(
(persistedAddressEntry.getPubKeyHash())); (DeterministicKey) wallet.findKeyFromPubHash(persistedAddressEntry.getPubKeyHash()));
} }
addressEntryList = persistedAddressEntryList; addressEntryList = persistedAddressEntryList;
registrationAddressEntry = addressEntryList.get(0); registrationAddressEntry = addressEntryList.get(0);
@ -279,8 +279,8 @@ public class WalletFacade {
} }
public AddressEntry getAddressInfoByTradeID(String offerId) { public AddressEntry getAddressInfoByTradeID(String offerId) {
Optional<AddressEntry> addressEntry = getAddressEntryList().stream().filter(e -> offerId.equals(e.getOfferId Optional<AddressEntry> addressEntry = getAddressEntryList().stream().filter(e ->
())).findFirst(); offerId.equals(e.getOfferId())).findFirst();
if (addressEntry.isPresent()) if (addressEntry.isPresent())
return addressEntry.get(); return addressEntry.get();
@ -318,8 +318,8 @@ public class WalletFacade {
List<TransactionConfidence> transactionConfidenceList = new ArrayList<>(); List<TransactionConfidence> transactionConfidenceList = new ArrayList<>();
Set<Transaction> transactions = wallet.getTransactions(true); Set<Transaction> transactions = wallet.getTransactions(true);
if (transactions != null) { if (transactions != null) {
transactionConfidenceList.addAll(transactions.stream().map(tx -> getTransactionConfidence(tx, transactionConfidenceList.addAll(transactions.stream().map(tx ->
address)).collect(Collectors.toList())); getTransactionConfidence(tx, address)).collect(Collectors.toList()));
/* same as: /* same as:
for (Transaction tx : transactions) for (Transaction tx : transactions)
{ {
@ -345,8 +345,8 @@ public class WalletFacade {
List<TransactionOutput> mergedOutputs = getOutputsWithConnectedOutputs(tx); List<TransactionOutput> mergedOutputs = getOutputsWithConnectedOutputs(tx);
List<TransactionConfidence> transactionConfidenceList = new ArrayList<>(); List<TransactionConfidence> transactionConfidenceList = new ArrayList<>();
mergedOutputs.stream().filter(e -> e.getScriptPubKey().isSentToAddress() || e.getScriptPubKey().isSentToP2SH mergedOutputs.stream().filter(e -> e.getScriptPubKey().isSentToAddress() ||
()).forEach(transactionOutput -> { e.getScriptPubKey().isSentToP2SH()).forEach(transactionOutput -> {
Address outputAddress = transactionOutput.getScriptPubKey().getToAddress(params); Address outputAddress = transactionOutput.getScriptPubKey().getToAddress(params);
if (address.equals(outputAddress)) { if (address.equals(outputAddress)) {
transactionConfidenceList.add(tx.getConfidence()); transactionConfidenceList.add(tx.getConfidence());
@ -356,8 +356,8 @@ public class WalletFacade {
same as: same as:
for (TransactionOutput transactionOutput : mergedOutputs) for (TransactionOutput transactionOutput : mergedOutputs)
{ {
if (transactionOutput.getScriptPubKey().isSentToAddress() || transactionOutput.getScriptPubKey() if (transactionOutput.getScriptPubKey().isSentToAddress() ||
.isSentToP2SH()) transactionOutput.getScriptPubKey().isSentToP2SH())
{ {
Address outputAddress = transactionOutput.getScriptPubKey().getToAddress(params); Address outputAddress = transactionOutput.getScriptPubKey().getToAddress(params);
if (address.equals(outputAddress)) if (address.equals(outputAddress))
@ -398,8 +398,8 @@ public class WalletFacade {
if (transactionConfidence == null || if (transactionConfidence == null ||
confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.PENDING) || confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.PENDING) ||
(confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.BUILDING) && (confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.BUILDING) &&
transactionConfidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType transactionConfidence.getConfidenceType().equals(
.BUILDING) && TransactionConfidence.ConfidenceType.BUILDING) &&
confidence.getDepthInBlocks() < transactionConfidence.getDepthInBlocks())) { confidence.getDepthInBlocks() < transactionConfidence.getDepthInBlocks())) {
transactionConfidence = confidence; transactionConfidence = confidence;
} }
@ -415,8 +415,8 @@ public class WalletFacade {
if (getRegistrationAddressEntry() != null) { if (getRegistrationAddressEntry() != null) {
transactionConfidence = getConfidenceForAddress(getRegistrationAddressEntry().getAddress()); transactionConfidence = getConfidenceForAddress(getRegistrationAddressEntry().getAddress());
} }
return transactionConfidence != null && transactionConfidence.getConfidenceType().equals return transactionConfidence != null &&
(TransactionConfidence.ConfidenceType.BUILDING); transactionConfidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.BUILDING);
} }
@ -507,12 +507,13 @@ public class WalletFacade {
Transaction tx = new Transaction(params); Transaction tx = new Transaction(params);
byte[] data = cryptoFacade.getEmbeddedAccountRegistrationData(getRegistrationAddressEntry().getKey(), byte[] data = cryptoFacade.getEmbeddedAccountRegistrationData(
stringifiedBankAccounts); getRegistrationAddressEntry().getKey(), stringifiedBankAccounts);
tx.addOutput(Transaction.MIN_NONDUST_OUTPUT, new ScriptBuilder().op(OP_RETURN).data(data).build()); tx.addOutput(Transaction.MIN_NONDUST_OUTPUT, new ScriptBuilder().op(OP_RETURN).data(data).build());
Coin fee = FeePolicy.ACCOUNT_REGISTRATION_FEE.subtract(Transaction.MIN_NONDUST_OUTPUT).subtract(FeePolicy Coin fee = FeePolicy.ACCOUNT_REGISTRATION_FEE
.TX_FEE); .subtract(Transaction.MIN_NONDUST_OUTPUT)
.subtract(FeePolicy.TX_FEE);
log.trace("fee: " + fee.toFriendlyString()); log.trace("fee: " + fee.toFriendlyString());
tx.addOutput(fee, feePolicy.getAddressForRegistrationFee()); tx.addOutput(fee, feePolicy.getAddressForRegistrationFee());
@ -842,16 +843,14 @@ public class WalletFacade {
log.trace("offerersFirstTx = " + offerersFirstTx); log.trace("offerersFirstTx = " + offerersFirstTx);
// add input // add input
Transaction offerersFirstTxConnOut = wallet.getTransaction(offerersFirstTx.getInput(0).getOutpoint().getHash Transaction offerersFirstTxConnOut = wallet.getTransaction(offerersFirstTx.getInput(0).getOutpoint().getHash());
()); // pass that around! TransactionOutPoint offerersFirstTxOutPoint =
TransactionOutPoint offerersFirstTxOutPoint = new TransactionOutPoint(params, offererTxOutIndex, new TransactionOutPoint(params, offererTxOutIndex, offerersFirstTxConnOut);
offerersFirstTxConnOut);
//TransactionInput offerersFirstTxInput = new TransactionInput(params, tx, //TransactionInput offerersFirstTxInput = new TransactionInput(params, tx,
// offerersFirstTx.getInput(0).getScriptBytes(), offerersFirstTxOutPoint); // pass that around! // offerersFirstTx.getInput(0).getScriptBytes(), offerersFirstTxOutPoint); // pass that around!
// getScriptBytes = // getScriptBytes =
// empty bytes array // empty bytes array
TransactionInput offerersFirstTxInput = new TransactionInput(params, tx, new byte[]{}, TransactionInput offerersFirstTxInput = new TransactionInput(params, tx, new byte[]{}, offerersFirstTxOutPoint);
offerersFirstTxOutPoint); // pass that around! getScriptBytes = empty bytes array
offerersFirstTxInput.setParent(tx); offerersFirstTxInput.setParent(tx);
tx.addInput(offerersFirstTxInput); tx.addInput(offerersFirstTxInput);
@ -863,10 +862,10 @@ public class WalletFacade {
// add input // add input
Transaction takersSignedTxConnOut = new Transaction(params, Utils.parseAsHexOrBase58(takersSignedConnOutAsHex)); Transaction takersSignedTxConnOut = new Transaction(params, Utils.parseAsHexOrBase58(takersSignedConnOutAsHex));
TransactionOutPoint takersSignedTxOutPoint = new TransactionOutPoint(params, takerTxOutIndex, TransactionOutPoint takersSignedTxOutPoint =
takersSignedTxConnOut); new TransactionOutPoint(params, takerTxOutIndex, takersSignedTxConnOut);
TransactionInput takersSignedTxInput = new TransactionInput(params, tx, TransactionInput takersSignedTxInput = new TransactionInput(
Utils.parseAsHexOrBase58(takersSignedScriptSigAsHex), takersSignedTxOutPoint); params, tx, Utils.parseAsHexOrBase58(takersSignedScriptSigAsHex), takersSignedTxOutPoint);
takersSignedTxInput.setParent(tx); takersSignedTxInput.setParent(tx);
tx.addInput(takersSignedTxInput); tx.addInput(takersSignedTxInput);
@ -965,8 +964,8 @@ public class WalletFacade {
Coin offererPaybackAmount, Coin offererPaybackAmount,
Coin takerPaybackAmount, Coin takerPaybackAmount,
String takerAddress, String takerAddress,
String tradeID) throws String tradeID)
AddressFormatException { throws AddressFormatException {
log.debug("offererCreatesAndSignsPayoutTx"); log.debug("offererCreatesAndSignsPayoutTx");
log.trace("inputs: "); log.trace("inputs: ");
log.trace("depositTxID=" + depositTxID); log.trace("depositTxID=" + depositTxID);
@ -1028,8 +1027,8 @@ public class WalletFacade {
ECKey.ECDSASignature takerSignature = getAddressInfoByTradeID(tradeID).getKey().sign(sigHash); ECKey.ECDSASignature takerSignature = getAddressInfoByTradeID(tradeID).getKey().sign(sigHash);
TransactionSignature takerTxSig = new TransactionSignature(takerSignature, Transaction.SigHash.ALL, false); TransactionSignature takerTxSig = new TransactionSignature(takerSignature, Transaction.SigHash.ALL, false);
ECKey.ECDSASignature offererSignature = new ECKey.ECDSASignature(new BigInteger(offererSignatureR), ECKey.ECDSASignature offererSignature =
new BigInteger(offererSignatureS)); new ECKey.ECDSASignature(new BigInteger(offererSignatureR), new BigInteger(offererSignatureS));
TransactionSignature offererTxSig = new TransactionSignature(offererSignature, Transaction.SigHash.ALL, false); TransactionSignature offererTxSig = new TransactionSignature(offererSignature, Transaction.SigHash.ALL, false);
Script inputScript = ScriptBuilder.createMultiSigInputScript(ImmutableList.of(offererTxSig, takerTxSig)); Script inputScript = ScriptBuilder.createMultiSigInputScript(ImmutableList.of(offererTxSig, takerTxSig));

View file

@ -70,8 +70,8 @@ public class CryptoFacade {
public byte[] getEmbeddedAccountRegistrationData(ECKey registrationKey, String stringifiedBankAccounts) { public byte[] getEmbeddedAccountRegistrationData(ECKey registrationKey, String stringifiedBankAccounts) {
String signedBankAccountIDs = signMessage(registrationKey, stringifiedBankAccounts, null); String signedBankAccountIDs = signMessage(registrationKey, stringifiedBankAccounts, null);
return Utils.sha256hash160(concatenateChunks(stringifiedBankAccounts, signedBankAccountIDs).getBytes(Charsets return Utils.sha256hash160(
.UTF_8)); concatenateChunks(stringifiedBankAccounts, signedBankAccountIDs).getBytes(Charsets.UTF_8));
} }
public String signContract(ECKey key, String contractAsJson) { public String signContract(ECKey key, String contractAsJson) {

View file

@ -74,8 +74,8 @@ public class BitSquareModule extends AbstractModule {
// bind(Boolean.class).annotatedWith(Names.named("useDiskStorage")).toInstance(new Boolean(true)); // bind(Boolean.class).annotatedWith(Names.named("useDiskStorage")).toInstance(new Boolean(true));
bind(Boolean.class).annotatedWith(Names.named("useDiskStorage")).toInstance(new Boolean(false)); bind(Boolean.class).annotatedWith(Names.named("useDiskStorage")).toInstance(new Boolean(false));
bind(SeedNodeAddress.StaticSeedNodeAddresses.class).annotatedWith(Names.named("defaultSeedNode")).toInstance bind(SeedNodeAddress.StaticSeedNodeAddresses.class).annotatedWith(
(SeedNodeAddress.StaticSeedNodeAddresses.LOCALHOST); Names.named("defaultSeedNode")).toInstance(SeedNodeAddress.StaticSeedNodeAddresses.LOCALHOST);
// bind(SeedNodeAddress.StaticSeedNodeAddresses.class).annotatedWith(Names.named("defaultSeedNode")) // bind(SeedNodeAddress.StaticSeedNodeAddresses.class).annotatedWith(Names.named("defaultSeedNode"))
// .toInstance(SeedNodeAddress.StaticSeedNodeAddresses.DIGITAL_OCEAN); // .toInstance(SeedNodeAddress.StaticSeedNodeAddresses.DIGITAL_OCEAN);
} }

View file

@ -57,12 +57,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* Holds the splash screen and the application views. * Holds the splash screen and the application views. It builds up all the views and initializes the facades.
* It builds up all the views and initializes the facades. * We use a sequence of Platform.runLater cascaded calls to make the startup more smooth, otherwise the rendering is
* We use a sequence of Platform.runLater cascaded calls to make the startup more smooth, * frozen for too long. Pre-loading of views is not implemented yet, and after a quick test it seemed that it does not
* otherwise the rendering is frozen for too long. * give much improvements.
* Pre-loading of views is not implemented yet, and after a quick test it seemed that it does not give much
* improvements.
*/ */
public class MainController extends ViewController { public class MainController extends ViewController {
private static final Logger log = LoggerFactory.getLogger(MainController.class); private static final Logger log = LoggerFactory.getLogger(MainController.class);
@ -282,11 +280,9 @@ public class MainController extends ViewController {
user.getBankAccountsSizeProperty().addListener((observableValue, oldValue, newValue) -> { user.getBankAccountsSizeProperty().addListener((observableValue, oldValue, newValue) -> {
if ((int) newValue == 2) if ((int) newValue == 2)
viewBuilder.rightNavPane.getChildren().add(1, accountComboBoxHolder);// accountComboBoxHolder viewBuilder.rightNavPane.getChildren().add(1, accountComboBoxHolder);
// .setVisible(true);
else if ((int) newValue < 2) else if ((int) newValue < 2)
viewBuilder.rightNavPane.getChildren().remove(accountComboBoxHolder);//accountComboBoxHolder viewBuilder.rightNavPane.getChildren().remove(accountComboBoxHolder);
// .setVisible(false);
}); });
settingsButton = addNavButton(viewBuilder.rightNavPane, "Settings", NavigationItem.SETTINGS); settingsButton = addNavButton(viewBuilder.rightNavPane, "Settings", NavigationItem.SETTINGS);
@ -387,8 +383,8 @@ public class MainController extends ViewController {
} }
private void addAccountComboBox(Pane parent) { private void addAccountComboBox(Pane parent) {
final ComboBox<BankAccount> accountComboBox = new ComboBox<>(FXCollections.observableArrayList(user final ComboBox<BankAccount> accountComboBox =
.getBankAccounts())); new ComboBox<>(FXCollections.observableArrayList(user.getBankAccounts()));
accountComboBox.setId("nav-account-combo-box"); accountComboBox.setId("nav-account-combo-box");
accountComboBox.setLayoutY(12); accountComboBox.setLayoutY(12);
if (user.getCurrentBankAccount() != null) if (user.getCurrentBankAccount() != null)
@ -406,8 +402,8 @@ public class MainController extends ViewController {
} }
}); });
user.getSelectedBankAccountIndexProperty().addListener(observable -> accountComboBox.getSelectionModel() user.getSelectedBankAccountIndexProperty().addListener(observable ->
.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

@ -133,8 +133,8 @@ public class ArbitratorProfileController extends CachedViewController {
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(BitSquareFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods())); methodsTextField.setText(BitSquareFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods()));
idVerificationsTextField.setText(BitSquareFormatter.arbitrationIDVerificationsToString(arbitrator idVerificationsTextField.setText(
.getIdVerifications())); BitSquareFormatter.arbitrationIDVerificationsToString(arbitrator.getIdVerifications()));
webPageTextField.setText(arbitrator.getWebUrl()); webPageTextField.setText(arbitrator.getWebUrl());
descriptionTextArea.setText(arbitrator.getDescription()); descriptionTextArea.setText(arbitrator.getDescription());
} }

View file

@ -138,8 +138,8 @@ public class ArbitratorRegistrationController extends CachedViewController {
} }
}); });
idTypeComboBox.setItems(FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator.ID_TYPE idTypeComboBox.setItems(FXCollections.observableArrayList(
.class)))); new ArrayList<>(EnumSet.allOf(Arbitrator.ID_TYPE.class))));
idTypeComboBox.setConverter(new StringConverter<Arbitrator.ID_TYPE>() { idTypeComboBox.setConverter(new StringConverter<Arbitrator.ID_TYPE>() {
@Override @Override
@ -170,8 +170,8 @@ public class ArbitratorRegistrationController extends CachedViewController {
} }
}); });
idVerificationsComboBox.setItems(FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator idVerificationsComboBox.setItems(
.ID_VERIFICATION.class)))); FXCollections.observableArrayList(new ArrayList<>(EnumSet.allOf(Arbitrator.ID_VERIFICATION.class))));
idVerificationsComboBox.setConverter(new StringConverter<Arbitrator.ID_VERIFICATION>() { idVerificationsComboBox.setConverter(new StringConverter<Arbitrator.ID_VERIFICATION>() {
@Override @Override
@ -300,8 +300,8 @@ public class ArbitratorRegistrationController extends CachedViewController {
if (idVerification != null) { if (idVerification != null) {
if (!idVerificationList.contains(idVerification)) { if (!idVerificationList.contains(idVerification)) {
idVerificationList.add(idVerification); idVerificationList.add(idVerification);
idVerificationsTextField.setText(BitSquareFormatter.arbitrationIDVerificationsToString idVerificationsTextField.setText(
(idVerificationList)); BitSquareFormatter.arbitrationIDVerificationsToString(idVerificationList));
} }
} }
@ -342,19 +342,16 @@ 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\n" + infoLabel.setText("You need to pay 10 x the max. trading volume as collateral.\n\nThat payment will be " +
"That payment will be locked into a MultiSig fund and be refunded when you leave the arbitration pool" + "locked into a MultiSig fund and be refunded when you leave the arbitration pool.\nIn case of fraud " +
".\n" + "(collusion, not fulfilling the min. dispute quality requirements) you will lose your collateral.\n" +
"In case of fraud (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\n" + "resolution.\n\nPlease pay in " + arbitrator.getMaxTradeVolume() * 10 + " BTC");
"Please pay in " + arbitrator.getMaxTradeVolume() * 10 + " BTC");
String collateralAddress = walletFacade.getRegistrationAddressEntry() != null ? walletFacade String collateralAddress = walletFacade.getRegistrationAddressEntry() != null ?
.getRegistrationAddressEntry().toString() : ""; walletFacade.getRegistrationAddressEntry().toString() : "";
collateralAddressTextField.setText(collateralAddress); collateralAddressTextField.setText(collateralAddress);
AwesomeDude.setIcon(copyIcon, AwesomeIcon.COPY); AwesomeDude.setIcon(copyIcon, AwesomeIcon.COPY);
@ -365,8 +362,8 @@ public class ArbitratorRegistrationController extends CachedViewController {
clipboard.setContent(content); clipboard.setContent(content);
}); });
confidenceDisplay = new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, balanceTextField, confidenceDisplay = new ConfidenceDisplay(
progressIndicator); walletFacade.getWallet(), confirmationLabel, balanceTextField, progressIndicator);
paymentDoneButton.setDisable(walletFacade.getArbitratorDepositBalance().isZero()); paymentDoneButton.setDisable(walletFacade.getArbitratorDepositBalance().isZero());
log.debug("getArbitratorDepositBalance " + walletFacade.getArbitratorDepositBalance()); log.debug("getArbitratorDepositBalance " + walletFacade.getArbitratorDepositBalance());
walletFacade.getWallet().addEventListener(new WalletEventListener() { walletFacade.getWallet().addEventListener(new WalletEventListener() {
@ -432,8 +429,8 @@ public class ArbitratorRegistrationController extends CachedViewController {
arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee())); arbitrationFeeTextField.setText(String.valueOf(arbitrator.getArbitrationFee()));
minArbitrationFeeTextField.setText(String.valueOf(arbitrator.getMinArbitrationFee())); minArbitrationFeeTextField.setText(String.valueOf(arbitrator.getMinArbitrationFee()));
methodsTextField.setText(BitSquareFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods())); methodsTextField.setText(BitSquareFormatter.arbitrationMethodsToString(arbitrator.getArbitrationMethods()));
idVerificationsTextField.setText(BitSquareFormatter.arbitrationIDVerificationsToString(arbitrator idVerificationsTextField.setText(
.getIdVerifications())); BitSquareFormatter.arbitrationIDVerificationsToString(arbitrator.getIdVerifications()));
webPageTextField.setText(arbitrator.getWebUrl()); webPageTextField.setText(arbitrator.getWebUrl());
descriptionTextArea.setText(arbitrator.getDescription()); descriptionTextArea.setText(arbitrator.getDescription());
@ -447,13 +444,11 @@ public class ArbitratorRegistrationController extends CachedViewController {
private Arbitrator getEditedArbitrator() { private Arbitrator getEditedArbitrator() {
try { try {
BitSquareValidator.textFieldsNotEmptyWithReset(nameTextField, idTypeTextField, languagesTextField, BitSquareValidator.textFieldsNotEmptyWithReset(
methodsTextField, idVerificationsTextField); nameTextField, idTypeTextField, languagesTextField, methodsTextField, idVerificationsTextField);
BitSquareValidator.textFieldsHasDoubleValueWithReset(maxTradeVolumeTextField, BitSquareValidator.textFieldsHasDoubleValueWithReset(
passiveServiceFeeTextField, maxTradeVolumeTextField, passiveServiceFeeTextField, minPassiveServiceFeeTextField,
minPassiveServiceFeeTextField, arbitrationFeeTextField, minArbitrationFeeTextField);
arbitrationFeeTextField,
minArbitrationFeeTextField);
String pubKeyAsHex = walletFacade.getArbitratorDepositAddressEntry().getPubKeyAsHexString(); String pubKeyAsHex = walletFacade.getArbitratorDepositAddressEntry().getPubKeyAsHexString();
String messagePubKeyAsHex = DSAKeyUtil.getHexStringFromPublicKey(user.getMessagePublicKey()); String messagePubKeyAsHex = DSAKeyUtil.getHexStringFromPublicKey(user.getMessagePublicKey());

View file

@ -38,7 +38,11 @@ public class Popups {
} }
public static void openInformationPopup(String title, String message, String masthead) { public static void openInformationPopup(String title, String message, String masthead) {
Dialogs.create().owner(BitSquare.getPrimaryStage()).title(title).message(message).masthead(masthead) Dialogs.create()
.owner(BitSquare.getPrimaryStage())
.title(title)
.message(message)
.masthead(masthead)
.showInformation(); .showInformation();
} }
@ -55,8 +59,13 @@ public class Popups {
} }
public static Action openConfirmPopup(String title, String message, String masthead, List<Action> actions) { public static Action openConfirmPopup(String title, String message, String masthead, List<Action> actions) {
return Dialogs.create().owner(BitSquare.getPrimaryStage()).title(title).message(message).masthead(masthead) return Dialogs.create()
.actions(actions).showConfirm(); .owner(BitSquare.getPrimaryStage())
.title(title)
.message(message)
.masthead(masthead)
.actions(actions)
.showConfirm();
} }
// Warning // Warning
@ -69,7 +78,11 @@ public class Popups {
} }
public static void openWarningPopup(String title, String message, String masthead) { public static void openWarningPopup(String title, String message, String masthead) {
Dialogs.create().owner(BitSquare.getPrimaryStage()).title(title).message(message).masthead(masthead) Dialogs.create()
.owner(BitSquare.getPrimaryStage())
.title(title)
.message(message)
.masthead(masthead)
.showWarning(); .showWarning();
} }
@ -83,7 +96,11 @@ public class Popups {
} }
public static Action openErrorPopup(String title, String message, String masthead) { public static Action openErrorPopup(String title, String message, String masthead) {
return Dialogs.create().owner(BitSquare.getPrimaryStage()).title(title).message(message).masthead(masthead) return Dialogs.create()
.owner(BitSquare.getPrimaryStage())
.title(title)
.message(message)
.masthead(masthead)
.showError(); .showError();
} }
@ -97,7 +114,11 @@ public class Popups {
} }
public static Action openExceptionPopup(Throwable throwable, String title, String message, String masthead) { public static Action openExceptionPopup(Throwable throwable, String title, String message, String masthead) {
return Dialogs.create().owner(BitSquare.getPrimaryStage()).title(title).message(message).masthead(masthead) return Dialogs.create()
.owner(BitSquare.getPrimaryStage())
.title(title)
.message(message)
.masthead(masthead)
.showException(throwable); .showException(throwable);
} }
@ -132,7 +153,11 @@ public class Popups {
public static Action openRegistrationMissingPopup(String title, String message, String masthead, public static Action openRegistrationMissingPopup(String title, String message, String masthead,
List<Dialogs.CommandLink> commandLinks, int selectedIndex) { List<Dialogs.CommandLink> commandLinks, int selectedIndex) {
return Dialogs.create().owner(BitSquare.getPrimaryStage()).title(title).message(message).masthead(masthead) return Dialogs.create()
.owner(BitSquare.getPrimaryStage())
.title(title)
.message(message)
.masthead(masthead)
.showCommandLinks(commandLinks.get(selectedIndex), commandLinks); .showCommandLinks(commandLinks.get(selectedIndex), commandLinks);
} }
} }

View file

@ -135,8 +135,8 @@ public class ValidatingTextField extends TextField {
}); });
focusedProperty().addListener((ov, oldValue, newValue) -> { focusedProperty().addListener((ov, oldValue, newValue) -> {
if (validateOnFocusOut && needsValidationOnFocusOut && !newValue && getScene() != null && getScene() if (validateOnFocusOut && needsValidationOnFocusOut &&
.getWindow().isFocused()) !newValue && getScene() != null && getScene().getWindow().isFocused())
validate(getText()); validate(getText());
}); });

View file

@ -147,8 +147,8 @@ public class AddressTextField extends AnchorPane {
private String getBitcoinURI() { private String getBitcoinURI() {
Coin d = BitSquareFormatter.parseToCoin(amountToPay); Coin d = BitSquareFormatter.parseToCoin(amountToPay);
return BitcoinURI.convertToBitcoinURI(address, BitSquareFormatter.parseToCoin(amountToPay), return BitcoinURI.convertToBitcoinURI(
BitSquare.getAppName(), null); address, BitSquareFormatter.parseToCoin(amountToPay), BitSquare.getAppName(), null);
} }

View file

@ -127,8 +127,8 @@ public class BalanceTextField extends AnchorPane {
progressIndicator.setProgress(0); progressIndicator.setProgress(0);
break; break;
case PENDING: case PENDING:
progressIndicatorTooltip.setText("Seen by " + confidence.numBroadcastPeers() + " peer(s) / 0 " + progressIndicatorTooltip.setText(
"confirmations"); "Seen by " + confidence.numBroadcastPeers() + " peer(s) / 0 " + "confirmations");
progressIndicator.setProgress(-1.0); progressIndicator.setProgress(-1.0);
break; break;
case BUILDING: case BUILDING:

View file

@ -227,7 +227,8 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase<Confidence
public void invalidated(Observable valueModel) { public void invalidated(Observable valueModel) {
if (getSkinnable().isIndeterminate() && timelineNulled && spinner == null) { if (getSkinnable().isIndeterminate() && timelineNulled && spinner == null) {
timelineNulled = false; timelineNulled = false;
spinner = new IndeterminateSpinner(getSkinnable(), ConfidenceProgressIndicatorSkin.this, spinner = new IndeterminateSpinner(
getSkinnable(), ConfidenceProgressIndicatorSkin.this,
spinEnabled.get(), progressColor.get()); spinEnabled.get(), progressColor.get());
getChildren().add(spinner); getChildren().add(spinner);
} }
@ -260,7 +261,8 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase<Confidence
} else { } else {
if (getSkinnable().getScene() != null && getSkinnable().isIndeterminate()) { if (getSkinnable().getScene() != null && getSkinnable().isIndeterminate()) {
timelineNulled = false; timelineNulled = false;
spinner = new IndeterminateSpinner(getSkinnable(), ConfidenceProgressIndicatorSkin.this, spinner = new IndeterminateSpinner(
getSkinnable(), ConfidenceProgressIndicatorSkin.this,
spinEnabled.get(), progressColor.get()); spinEnabled.get(), progressColor.get());
getChildren().add(spinner); getChildren().add(spinner);
if (getSkinnable().impl_isTreeVisible()) { if (getSkinnable().impl_isTreeVisible()) {
@ -306,8 +308,8 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase<Confidence
spinner = null; spinner = null;
} }
// create determinateIndicator // create determinateIndicator
determinateIndicator = new ConfidenceProgressIndicatorSkin.DeterminateIndicator(control, this, determinateIndicator =
progressColor.get()); new ConfidenceProgressIndicatorSkin.DeterminateIndicator(control, this, progressColor.get());
getChildren().clear(); getChildren().clear();
getChildren().add(determinateIndicator); getChildren().add(determinateIndicator);
} }
@ -781,72 +783,70 @@ public class ConfidenceProgressIndicatorSkin extends BehaviorSkinBase<Confidence
private static class StyleableProperties { private static class StyleableProperties {
public static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; public static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES;
private static final CssMetaData<ConfidenceProgressIndicator, Paint> PROGRESS_COLOR = new private static final CssMetaData<ConfidenceProgressIndicator, Paint> PROGRESS_COLOR =
CssMetaData<ConfidenceProgressIndicator, Paint>("-fx-progress-color", new CssMetaData<ConfidenceProgressIndicator, Paint>(
PaintConverter.getInstance(), "-fx-progress-color", PaintConverter.getInstance(), null) {
null) {
@Override @Override
public boolean isSettable(ConfidenceProgressIndicator n) { public boolean isSettable(ConfidenceProgressIndicator n) {
final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin();
return skin.progressColor == null || !skin.progressColor.isBound(); return skin.progressColor == null || !skin.progressColor.isBound();
} }
@Override @Override
public StyleableProperty<Paint> getStyleableProperty(ConfidenceProgressIndicator n) { public StyleableProperty<Paint> getStyleableProperty(ConfidenceProgressIndicator n) {
final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin();
return (StyleableProperty<Paint>) skin.progressColor; return (StyleableProperty<Paint>) skin.progressColor;
} }
}; };
private static final CssMetaData<ConfidenceProgressIndicator, Number> INDETERMINATE_SEGMENT_COUNT = new private static final CssMetaData<ConfidenceProgressIndicator, Number> INDETERMINATE_SEGMENT_COUNT =
CssMetaData<ConfidenceProgressIndicator, Number>("-fx-indeterminate-segment-count", new CssMetaData<ConfidenceProgressIndicator, Number>(
SizeConverter.getInstance(), "-fx-indeterminate-segment-count", SizeConverter.getInstance(), 8) {
8) {
@Override @Override
public void set(ConfidenceProgressIndicator node, Number value, StyleOrigin origin) { public void set(ConfidenceProgressIndicator node, Number value, StyleOrigin origin) {
super.set(node, value.intValue(), origin); super.set(node, value.intValue(), origin);
} }
@Override @Override
public boolean isSettable(ConfidenceProgressIndicator n) { public boolean isSettable(ConfidenceProgressIndicator n) {
final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin();
return skin.indeterminateSegmentCount == null || !skin.indeterminateSegmentCount.isBound(); return skin.indeterminateSegmentCount == null || !skin.indeterminateSegmentCount.isBound();
} }
@Override @Override
public StyleableProperty<Number> getStyleableProperty(ConfidenceProgressIndicator n) { public StyleableProperty<Number> getStyleableProperty(ConfidenceProgressIndicator n) {
final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin(); final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) n.getSkin();
return (StyleableProperty<Number>) skin.indeterminateSegmentCount; return (StyleableProperty<Number>) skin.indeterminateSegmentCount;
} }
}; };
private static final CssMetaData<ConfidenceProgressIndicator, Boolean> SPIN_ENABLED = new private static final CssMetaData<ConfidenceProgressIndicator, Boolean> SPIN_ENABLED = new
CssMetaData<ConfidenceProgressIndicator, Boolean>("-fx-spin-enabled", CssMetaData<ConfidenceProgressIndicator, Boolean>("-fx-spin-enabled",
BooleanConverter.getInstance(), BooleanConverter.getInstance(),
Boolean.FALSE) { Boolean.FALSE) {
@Override @Override
public boolean isSettable(ConfidenceProgressIndicator node) { public boolean isSettable(ConfidenceProgressIndicator node) {
final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin(); final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin();
return skin.spinEnabled == null || !skin.spinEnabled.isBound(); return skin.spinEnabled == null || !skin.spinEnabled.isBound();
} }
@Override @Override
public StyleableProperty<Boolean> getStyleableProperty(ConfidenceProgressIndicator node) { public StyleableProperty<Boolean> getStyleableProperty(ConfidenceProgressIndicator node) {
final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin(); final ConfidenceProgressIndicatorSkin skin = (ConfidenceProgressIndicatorSkin) node.getSkin();
return (StyleableProperty<Boolean>) skin.spinEnabled; return (StyleableProperty<Boolean>) skin.spinEnabled;
} }
}; };
static { static {
final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(SkinBase.getClassCssMetaData final List<CssMetaData<? extends Styleable, ?>> styleables =
()); new ArrayList<>(SkinBase.getClassCssMetaData());
styleables.add(PROGRESS_COLOR); styleables.add(PROGRESS_COLOR);
styleables.add(INDETERMINATE_SEGMENT_COUNT); styleables.add(INDETERMINATE_SEGMENT_COUNT);
styleables.add(SPIN_ENABLED); styleables.add(SPIN_ENABLED);

View file

@ -33,8 +33,8 @@ public class ProcessStepItem {
this(label, color, false); this(label, color, false);
} }
private ProcessStepItem(String label, Paint color, @SuppressWarnings("SameParameterValue") boolean private ProcessStepItem(String label, Paint color,
hasProgressIndicator) { @SuppressWarnings("SameParameterValue") boolean hasProgressIndicator) {
this.label = label; this.label = label;
this.color = color; this.color = color;
this.progressIndicator = hasProgressIndicator; this.progressIndicator = hasProgressIndicator;

View file

@ -54,8 +54,9 @@ public class FundsController extends CachedViewController {
public void initialize(URL url, ResourceBundle rb) { public void initialize(URL url, ResourceBundle rb) {
super.initialize(url, rb); super.initialize(url, rb);
((CachingTabPane) root).initialize(this, persistence, NavigationItem.DEPOSIT.getFxmlUrl(), ((CachingTabPane) root).initialize(
NavigationItem.WITHDRAWAL.getFxmlUrl(), NavigationItem.TRANSACTIONS.getFxmlUrl()); this, persistence, NavigationItem.DEPOSIT.getFxmlUrl(), NavigationItem.WITHDRAWAL.getFxmlUrl(),
NavigationItem.TRANSACTIONS.getFxmlUrl());
} }
@Override @Override

View file

@ -93,8 +93,8 @@ public class DepositController extends CachedViewController {
List<AddressEntry> addressEntryList = walletFacade.getAddressEntryList(); List<AddressEntry> addressEntryList = walletFacade.getAddressEntryList();
addressList = FXCollections.observableArrayList(); addressList = FXCollections.observableArrayList();
addressList.addAll(addressEntryList.stream().map(anAddressEntryList -> new DepositListItem addressList.addAll(addressEntryList.stream().map(anAddressEntryList ->
(anAddressEntryList, walletFacade)).collect(Collectors.toList())); new DepositListItem(anAddressEntryList, walletFacade)).collect(Collectors.toList()));
tableView.setItems(addressList); tableView.setItems(addressList);
} }
@ -136,8 +136,8 @@ public class DepositController extends CachedViewController {
Tooltip tooltip = new Tooltip(item.getAddressEntry().getOfferId()); Tooltip tooltip = new Tooltip(item.getAddressEntry().getOfferId());
Tooltip.install(hyperlink, tooltip); Tooltip.install(hyperlink, tooltip);
hyperlink.setOnAction(event -> log.info("Show trade details " + item.getAddressEntry hyperlink.setOnAction(event ->
().getOfferId())); log.info("Show trade details " + item.getAddressEntry().getOfferId()));
} }
setGraphic(hyperlink); setGraphic(hyperlink);
} else { } else {
@ -152,63 +152,63 @@ public class DepositController extends CachedViewController {
private void setBalanceColumnCellFactory() { private void setBalanceColumnCellFactory() {
balanceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); balanceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue()));
balanceColumn.setCellFactory(new Callback<TableColumn<String, DepositListItem>, TableCell<String, balanceColumn.setCellFactory(
DepositListItem>>() { new Callback<TableColumn<String, DepositListItem>, TableCell<String, DepositListItem>>() {
@Override
public TableCell<String, DepositListItem> call(TableColumn<String, DepositListItem> column) {
return new TableCell<String, DepositListItem>() {
@Override @Override
public void updateItem(final DepositListItem item, boolean empty) { public TableCell<String, DepositListItem> call(TableColumn<String, DepositListItem> column) {
super.updateItem(item, empty); return new TableCell<String, DepositListItem>() {
@Override
public void updateItem(final DepositListItem item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty) { if (item != null && !empty) {
setGraphic(item.getBalanceLabel()); setGraphic(item.getBalanceLabel());
} else { } else {
setGraphic(null); setGraphic(null);
} }
}
};
} }
}; });
}
});
} }
private void setCopyColumnCellFactory() { private void setCopyColumnCellFactory() {
copyColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); copyColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue()));
copyColumn.setCellFactory(new Callback<TableColumn<String, DepositListItem>, TableCell<String, copyColumn.setCellFactory(
DepositListItem>>() { new Callback<TableColumn<String, DepositListItem>, TableCell<String, DepositListItem>>() {
@Override
public TableCell<String, DepositListItem> call(TableColumn<String, DepositListItem> column) {
return new TableCell<String, DepositListItem>() {
final Label copyIcon = new Label();
{
copyIcon.getStyleClass().add("copy-icon");
AwesomeDude.setIcon(copyIcon, AwesomeIcon.COPY);
Tooltip.install(copyIcon, new Tooltip("Copy address to clipboard"));
}
@Override @Override
public void updateItem(final DepositListItem item, boolean empty) { public TableCell<String, DepositListItem> call(TableColumn<String, DepositListItem> column) {
super.updateItem(item, empty); return new TableCell<String, DepositListItem>() {
final Label copyIcon = new Label();
if (item != null && !empty) { {
setGraphic(copyIcon); copyIcon.getStyleClass().add("copy-icon");
copyIcon.setOnMouseClicked(e -> { AwesomeDude.setIcon(copyIcon, AwesomeIcon.COPY);
Clipboard clipboard = Clipboard.getSystemClipboard(); Tooltip.install(copyIcon, new Tooltip("Copy address to clipboard"));
ClipboardContent content = new ClipboardContent(); }
content.putString(item.addressStringProperty().get());
clipboard.setContent(content);
});
} else { @Override
setGraphic(null); public void updateItem(final DepositListItem item, boolean empty) {
} super.updateItem(item, empty);
if (item != null && !empty) {
setGraphic(copyIcon);
copyIcon.setOnMouseClicked(e -> {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
content.putString(item.addressStringProperty().get());
clipboard.setContent(content);
});
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
private void setConfidenceColumnCellFactory() { private void setConfidenceColumnCellFactory() {

View file

@ -88,8 +88,8 @@ public class TransactionsController extends CachedViewController {
List<Transaction> transactions = walletFacade.getWallet().getRecentTransactions(10000, true); List<Transaction> transactions = walletFacade.getWallet().getRecentTransactions(10000, true);
transactionsListItems = FXCollections.observableArrayList(); transactionsListItems = FXCollections.observableArrayList();
transactionsListItems.addAll(transactions.stream().map(transaction -> new TransactionsListItem(transaction, transactionsListItems.addAll(transactions.stream().map(transaction ->
walletFacade)).collect(Collectors.toList())); new TransactionsListItem(transaction, walletFacade)).collect(Collectors.toList()));
tableView.setItems(transactionsListItems); tableView.setItems(transactionsListItems);
} }
@ -111,56 +111,59 @@ public class TransactionsController extends CachedViewController {
private void setAddressColumnCellFactory() { private void setAddressColumnCellFactory() {
addressColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); addressColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue()));
addressColumn.setCellFactory(new Callback<TableColumn<String, TransactionsListItem>, TableCell<String, addressColumn.setCellFactory(
TransactionsListItem>>() { new Callback<TableColumn<String, TransactionsListItem>, TableCell<String, TransactionsListItem>>() {
@Override
public TableCell<String, TransactionsListItem> call(TableColumn<String, TransactionsListItem> column) {
return new TableCell<String, TransactionsListItem>() {
Hyperlink hyperlink;
@Override @Override
public void updateItem(final TransactionsListItem item, boolean empty) { public TableCell<String, TransactionsListItem> call(TableColumn<String,
super.updateItem(item, empty); TransactionsListItem> column) {
return new TableCell<String, TransactionsListItem>() {
Hyperlink hyperlink;
if (item != null && !empty) { @Override
hyperlink = new Hyperlink(item.getAddressString()); public void updateItem(final TransactionsListItem item, boolean empty) {
hyperlink.setId("id-link"); super.updateItem(item, empty);
hyperlink.setOnAction(event -> log.info("Show trade details " + item.getAddressString()));
setGraphic(hyperlink); if (item != null && !empty) {
} else { hyperlink = new Hyperlink(item.getAddressString());
setGraphic(null); hyperlink.setId("id-link");
setId(null); hyperlink.setOnAction(event -> log.info("Show trade details " + item
} .getAddressString()));
setGraphic(hyperlink);
} else {
setGraphic(null);
setId(null);
}
}
};
} }
}; });
}
});
} }
private void setConfidenceColumnCellFactory() { private void setConfidenceColumnCellFactory() {
confidenceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue confidenceColumn.setCellValueFactory((addressListItem) ->
())); new ReadOnlyObjectWrapper(addressListItem.getValue()));
confidenceColumn.setCellFactory(new Callback<TableColumn<String, TransactionsListItem>, TableCell<String, confidenceColumn.setCellFactory(
TransactionsListItem>>() { new Callback<TableColumn<String, TransactionsListItem>, TableCell<String, TransactionsListItem>>() {
@Override
public TableCell<String, TransactionsListItem> call(TableColumn<String, TransactionsListItem> column) {
return new TableCell<String, TransactionsListItem>() {
@Override @Override
public void updateItem(final TransactionsListItem item, boolean empty) { public TableCell<String, TransactionsListItem> call(TableColumn<String,
super.updateItem(item, empty); TransactionsListItem> column) {
return new TableCell<String, TransactionsListItem>() {
if (item != null && !empty) { @Override
setGraphic(item.getProgressIndicator()); public void updateItem(final TransactionsListItem item, boolean empty) {
} else { super.updateItem(item, empty);
setGraphic(null);
} if (item != null && !empty) {
setGraphic(item.getProgressIndicator());
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
} }

View file

@ -56,10 +56,10 @@ public class TransactionsListItem {
if (!transactionOutput.isMine(walletFacade.getWallet())) { if (!transactionOutput.isMine(walletFacade.getWallet())) {
type.set("Sent to"); type.set("Sent to");
if (transactionOutput.getScriptPubKey().isSentToAddress() || transactionOutput.getScriptPubKey() if (transactionOutput.getScriptPubKey().isSentToAddress() ||
.isPayToScriptHash()) { transactionOutput.getScriptPubKey().isPayToScriptHash()) {
address = transactionOutput.getScriptPubKey().getToAddress(walletFacade.getWallet().getParams address =
()); transactionOutput.getScriptPubKey().getToAddress(walletFacade.getWallet().getParams());
addressString = address.toString(); addressString = address.toString();
} else { } else {
addressString = "No sent to address script used."; addressString = "No sent to address script used.";
@ -73,10 +73,10 @@ public class TransactionsListItem {
for (TransactionOutput transactionOutput : transaction.getOutputs()) { for (TransactionOutput transactionOutput : transaction.getOutputs()) {
if (transactionOutput.isMine(walletFacade.getWallet())) { if (transactionOutput.isMine(walletFacade.getWallet())) {
if (transactionOutput.getScriptPubKey().isSentToAddress() || transactionOutput.getScriptPubKey() if (transactionOutput.getScriptPubKey().isSentToAddress() ||
.isPayToScriptHash()) { transactionOutput.getScriptPubKey().isPayToScriptHash()) {
address = transactionOutput.getScriptPubKey().getToAddress(walletFacade.getWallet().getParams address =
()); transactionOutput.getScriptPubKey().getToAddress(walletFacade.getWallet().getParams());
addressString = address.toString(); addressString = address.toString();
} else { } else {
addressString = "No sent to address script used."; addressString = "No sent to address script used.";

View file

@ -107,8 +107,8 @@ public class WithdrawalController extends CachedViewController {
tableView.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> { tableView.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
if (newValue != null) { if (newValue != null) {
BitSquareValidator.resetTextFields(withdrawFromTextField, withdrawToTextField, amountTextField, BitSquareValidator.resetTextFields(
changeAddressTextField); withdrawFromTextField, withdrawToTextField, amountTextField, changeAddressTextField);
if (Coin.ZERO.compareTo(newValue.getBalance()) <= 0) { if (Coin.ZERO.compareTo(newValue.getBalance()) <= 0) {
amountTextField.setText(newValue.getBalance().toPlainString()); amountTextField.setText(newValue.getBalance().toPlainString());
@ -125,8 +125,8 @@ 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 -> new WithdrawalListItem addressList.addAll(addressEntryList.stream().map(anAddressEntryList ->
(anAddressEntryList, walletFacade)).collect(Collectors.toList())); new WithdrawalListItem(anAddressEntryList, walletFacade)).collect(Collectors.toList()));
tableView.setItems(addressList); tableView.setItems(addressList);
} }
@ -139,8 +139,8 @@ public class WithdrawalController extends CachedViewController {
@FXML @FXML
public void onWithdraw() { public void onWithdraw() {
try { try {
BitSquareValidator.textFieldsNotEmpty(amountTextField, withdrawFromTextField, withdrawToTextField, BitSquareValidator.textFieldsNotEmpty(
changeAddressTextField); amountTextField, withdrawFromTextField, withdrawToTextField, changeAddressTextField);
BitSquareValidator.textFieldsHasDoubleValueWithReset(amountTextField); BitSquareValidator.textFieldsHasDoubleValueWithReset(amountTextField);
Coin amount = BitSquareFormatter.parseToCoin(amountTextField.getText()); Coin amount = BitSquareFormatter.parseToCoin(amountTextField.getText());
@ -148,8 +148,8 @@ public class WithdrawalController extends CachedViewController {
FutureCallback<Transaction> callback = new FutureCallback<Transaction>() { FutureCallback<Transaction> callback = new FutureCallback<Transaction>() {
@Override @Override
public void onSuccess(@javax.annotation.Nullable Transaction transaction) { public void onSuccess(@javax.annotation.Nullable Transaction transaction) {
BitSquareValidator.resetTextFields(withdrawFromTextField, withdrawToTextField, BitSquareValidator.resetTextFields(
amountTextField, changeAddressTextField); withdrawFromTextField, withdrawToTextField, amountTextField, changeAddressTextField);
if (transaction != null) { if (transaction != null) {
log.info("onWithdraw onSuccess txid:" + transaction.getHashAsString()); log.info("onWithdraw onSuccess txid:" + transaction.getHashAsString());
} }
@ -161,22 +161,23 @@ public class WithdrawalController extends CachedViewController {
} }
}; };
Action response = Popups.openConfirmPopup("Withdrawal request", "Confirm your request", Action response = Popups.openConfirmPopup(
"Your withdrawal request:\n\n" + "Withdrawal request", "Confirm your request",
"Amount: " + amountTextField.getText() + " BTC\n" + "Your withdrawal request:\n\n" + "Amount: " + amountTextField.getText() + " BTC\n" + "Sending" +
"Sending address: " + withdrawFromTextField.getText() + "\n" + " address: " + withdrawFromTextField.getText() + "\n" + "Receiving address: " +
"Receiving address: " + withdrawToTextField.getText() + "\n" + withdrawToTextField.getText() + "\n" + "Transaction fee: " +
"Transaction fee: " + BitSquareFormatter.formatCoinWithCode(FeePolicy.TX_FEE) + "\n" + BitSquareFormatter.formatCoinWithCode(FeePolicy.TX_FEE) + "\n" +
"You receive in total: " + BitSquareFormatter.formatCoinWithCode(amount.subtract(FeePolicy "You receive in total: " +
.TX_FEE)) + " BTC\n\n" + BitSquareFormatter.formatCoinWithCode(amount.subtract(FeePolicy.TX_FEE)) + " BTC\n\n" +
"Are you sure you withdraw that amount?"); "Are you sure you withdraw that amount?");
if (response == Dialog.Actions.OK) { if (response == Dialog.Actions.OK) {
try { try {
walletFacade.sendFunds(withdrawFromTextField.getText(), withdrawToTextField.getText(), walletFacade.sendFunds(
withdrawFromTextField.getText(), withdrawToTextField.getText(),
changeAddressTextField.getText(), amount, callback); changeAddressTextField.getText(), amount, callback);
} catch (AddressFormatException e) { } catch (AddressFormatException e) {
Popups.openErrorPopup("Address invalid", "The address is not correct. Please check the " + Popups.openErrorPopup("Address invalid",
"address format."); "The address is not correct. Please check the address format.");
} catch (InsufficientMoneyException e) { } catch (InsufficientMoneyException e) {
Popups.openInsufficientMoneyPopup(); Popups.openInsufficientMoneyPopup();
@ -186,8 +187,8 @@ public class WithdrawalController extends CachedViewController {
} }
} else { } else {
Popups.openErrorPopup("Insufficient amount", "The amount to transfer is lower the the transaction fee" + Popups.openErrorPopup("Insufficient amount",
" 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) {
@ -243,83 +244,83 @@ public class WithdrawalController extends CachedViewController {
private void setBalanceColumnCellFactory() { private void setBalanceColumnCellFactory() {
balanceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); balanceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue()));
balanceColumn.setCellFactory(new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, balanceColumn.setCellFactory(
WithdrawalListItem>>() { new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, WithdrawalListItem>>() {
@Override
public TableCell<String, WithdrawalListItem> call(TableColumn<String, WithdrawalListItem> column) {
return new TableCell<String, WithdrawalListItem>() {
@Override @Override
public void updateItem(final WithdrawalListItem item, boolean empty) { public TableCell<String, WithdrawalListItem> call(TableColumn<String, WithdrawalListItem> column) {
super.updateItem(item, empty); return new TableCell<String, WithdrawalListItem>() {
setGraphic((item != null && !empty) ? item.getBalanceLabel() : null); @Override
public void updateItem(final WithdrawalListItem item, boolean empty) {
super.updateItem(item, empty);
setGraphic((item != null && !empty) ? item.getBalanceLabel() : null);
}
};
} }
}; });
}
});
} }
private void setCopyColumnCellFactory() { private void setCopyColumnCellFactory() {
copyColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue())); copyColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue()));
copyColumn.setCellFactory(new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, copyColumn.setCellFactory(
WithdrawalListItem>>() { new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, WithdrawalListItem>>() {
@Override
public TableCell<String, WithdrawalListItem> call(TableColumn<String, WithdrawalListItem> column) {
return new TableCell<String, WithdrawalListItem>() {
final Label copyIcon = new Label();
{
copyIcon.getStyleClass().add("copy-icon");
AwesomeDude.setIcon(copyIcon, AwesomeIcon.COPY);
Tooltip.install(copyIcon, new Tooltip("Copy address to clipboard"));
}
@Override @Override
public void updateItem(final WithdrawalListItem item, boolean empty) { public TableCell<String, WithdrawalListItem> call(TableColumn<String, WithdrawalListItem> column) {
super.updateItem(item, empty); return new TableCell<String, WithdrawalListItem>() {
final Label copyIcon = new Label();
if (item != null && !empty) { {
setGraphic(copyIcon); copyIcon.getStyleClass().add("copy-icon");
copyIcon.setOnMouseClicked(e -> { AwesomeDude.setIcon(copyIcon, AwesomeIcon.COPY);
Clipboard clipboard = Clipboard.getSystemClipboard(); Tooltip.install(copyIcon, new Tooltip("Copy address to clipboard"));
ClipboardContent content = new ClipboardContent(); }
content.putString(item.addressStringProperty().get());
clipboard.setContent(content);
});
} else { @Override
setGraphic(null); public void updateItem(final WithdrawalListItem item, boolean empty) {
} super.updateItem(item, empty);
if (item != null && !empty) {
setGraphic(copyIcon);
copyIcon.setOnMouseClicked(e -> {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
content.putString(item.addressStringProperty().get());
clipboard.setContent(content);
});
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
private void setConfidenceColumnCellFactory() { private void setConfidenceColumnCellFactory() {
confidenceColumn.setCellValueFactory((addressListItem) -> new ReadOnlyObjectWrapper(addressListItem.getValue confidenceColumn.setCellValueFactory((addressListItem) ->
())); new ReadOnlyObjectWrapper(addressListItem.getValue()));
confidenceColumn.setCellFactory(new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, confidenceColumn.setCellFactory(
WithdrawalListItem>>() { new Callback<TableColumn<String, WithdrawalListItem>, TableCell<String, WithdrawalListItem>>() {
@Override
public TableCell<String, WithdrawalListItem> call(TableColumn<String, WithdrawalListItem> column) {
return new TableCell<String, WithdrawalListItem>() {
@Override @Override
public void updateItem(final WithdrawalListItem item, boolean empty) { public TableCell<String, WithdrawalListItem> call(TableColumn<String, WithdrawalListItem> column) {
super.updateItem(item, empty); return new TableCell<String, WithdrawalListItem>() {
if (item != null && !empty) { @Override
setGraphic(item.getProgressIndicator()); public void updateItem(final WithdrawalListItem item, boolean empty) {
} else { super.updateItem(item, empty);
setGraphic(null);
} if (item != null && !empty) {
setGraphic(item.getProgressIndicator());
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
} }

View file

@ -117,66 +117,66 @@ public class OfferController extends CachedViewController {
private void setOfferIdColumnColumnCellFactory() { private void setOfferIdColumnColumnCellFactory() {
offerIdColumn.setCellValueFactory((offerListItem) -> new ReadOnlyObjectWrapper(offerListItem.getValue())); offerIdColumn.setCellValueFactory((offerListItem) -> new ReadOnlyObjectWrapper(offerListItem.getValue()));
offerIdColumn.setCellFactory(new Callback<TableColumn<String, OfferListItem>, TableCell<String, offerIdColumn.setCellFactory(
OfferListItem>>() { new Callback<TableColumn<String, OfferListItem>, TableCell<String, OfferListItem>>() {
@Override
public TableCell<String, OfferListItem> call(TableColumn<String, OfferListItem> column) {
return new TableCell<String, OfferListItem>() {
Hyperlink hyperlink;
@Override @Override
public void updateItem(final OfferListItem item, boolean empty) { public TableCell<String, OfferListItem> call(TableColumn<String, OfferListItem> column) {
super.updateItem(item, empty); return new TableCell<String, OfferListItem>() {
Hyperlink hyperlink;
if (item != null && !empty) { @Override
hyperlink = new Hyperlink(item.getOfferId()); public void updateItem(final OfferListItem item, boolean empty) {
//hyperlink.getStyleClass().setAll("aaa"); super.updateItem(item, empty);
Tooltip tooltip = new Tooltip(item.getOfferId());
Tooltip.install(hyperlink, tooltip); if (item != null && !empty) {
hyperlink.setOnAction(event -> openOfferDetails(item)); hyperlink = new Hyperlink(item.getOfferId());
setGraphic(hyperlink); //hyperlink.getStyleClass().setAll("aaa");
} else { Tooltip tooltip = new Tooltip(item.getOfferId());
setGraphic(null); Tooltip.install(hyperlink, tooltip);
setId(null); hyperlink.setOnAction(event -> openOfferDetails(item));
} setGraphic(hyperlink);
} else {
setGraphic(null);
setId(null);
}
}
};
} }
}; });
}
});
} }
private void setRemoveColumnCellFactory() { private void setRemoveColumnCellFactory() {
removeColumn.setCellValueFactory((offerListItem) -> new ReadOnlyObjectWrapper(offerListItem.getValue())); removeColumn.setCellValueFactory((offerListItem) -> new ReadOnlyObjectWrapper(offerListItem.getValue()));
removeColumn.setCellFactory(new Callback<TableColumn<String, OfferListItem>, TableCell<String, removeColumn.setCellFactory(
OfferListItem>>() { new Callback<TableColumn<String, OfferListItem>, TableCell<String, OfferListItem>>() {
@Override
public TableCell<String, OfferListItem> call(TableColumn<String, OfferListItem> directionColumn) {
return new TableCell<String, OfferListItem>() {
final ImageView iconView = ImageUtil.getIconImageView(ImageUtil.REMOVE);
final Button button = new Button();
{
button.setText("Remove");
button.setGraphic(iconView);
button.setMinWidth(70);
}
@Override @Override
public void updateItem(final OfferListItem offerListItem, boolean empty) { public TableCell<String, OfferListItem> call(TableColumn<String, OfferListItem> directionColumn) {
super.updateItem(offerListItem, empty); return new TableCell<String, OfferListItem>() {
final ImageView iconView = ImageUtil.getIconImageView(ImageUtil.REMOVE);
final Button button = new Button();
if (offerListItem != null) { {
button.setOnAction(event -> removeOffer(offerListItem)); button.setText("Remove");
setGraphic(button); button.setGraphic(iconView);
} else { button.setMinWidth(70);
setGraphic(null); }
}
@Override
public void updateItem(final OfferListItem offerListItem, boolean empty) {
super.updateItem(offerListItem, empty);
if (offerListItem != null) {
button.setOnAction(event -> removeOffer(offerListItem));
setGraphic(button);
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
} }

View file

@ -37,10 +37,10 @@ public class OfferListItem {
this.date.set(BitSquareFormatter.formatDateTime(offer.getCreationDate())); this.date.set(BitSquareFormatter.formatDateTime(offer.getCreationDate()));
this.price.set(BitSquareFormatter.formatPrice(offer.getPrice())); this.price.set(BitSquareFormatter.formatPrice(offer.getPrice()));
this.amount.set(BitSquareFormatter.formatCoin(offer.getAmount()) + " (" + BitSquareFormatter.formatCoin(offer this.amount.set(BitSquareFormatter.formatCoin(
.getMinAmount()) + ")"); offer.getAmount()) + " (" + BitSquareFormatter.formatCoin(offer.getMinAmount()) + ")");
this.volume.set(BitSquareFormatter.formatVolumeWithMinVolume(offer.getOfferVolume(), this.volume.set(BitSquareFormatter.formatVolumeWithMinVolume(
offer.getMinOfferVolume())); offer.getOfferVolume(), offer.getMinOfferVolume()));
this.offerId = offer.getId(); this.offerId = offer.getId();
} }

View file

@ -72,23 +72,17 @@ public class PendingTradeController extends CachedViewController {
private Image sellIcon = ImageUtil.getIconImage(ImageUtil.SELL); private Image sellIcon = ImageUtil.getIconImage(ImageUtil.SELL);
private ConfidenceDisplay confidenceDisplay; private ConfidenceDisplay confidenceDisplay;
@FXML @FXML private TableView openTradesTable;
private TableView openTradesTable; @FXML private TableColumn<String, PendingTradesListItem> directionColumn, countryColumn, bankAccountTypeColumn,
@FXML
private TableColumn<String, PendingTradesListItem> directionColumn, countryColumn, bankAccountTypeColumn,
priceColumn, amountColumn, volumeColumn, statusColumn, selectColumn; priceColumn, amountColumn, volumeColumn, statusColumn, selectColumn;
@FXML @FXML private ConfidenceProgressIndicator progressIndicator;
private ConfidenceProgressIndicator progressIndicator; @FXML private Label txTitleLabel, txHeaderLabel, confirmationLabel, txIDCopyIcon, holderNameCopyIcon,
@FXML
private Label txTitleLabel, txHeaderLabel, confirmationLabel, txIDCopyIcon, holderNameCopyIcon,
primaryBankAccountIDCopyIcon, secondaryBankAccountIDCopyIcon, bankAccountDetailsHeaderLabel, primaryBankAccountIDCopyIcon, secondaryBankAccountIDCopyIcon, bankAccountDetailsHeaderLabel,
bankAccountTypeTitleLabel, holderNameTitleLabel, primaryBankAccountIDTitleLabel, bankAccountTypeTitleLabel, holderNameTitleLabel, primaryBankAccountIDTitleLabel,
secondaryBankAccountIDTitleLabel; secondaryBankAccountIDTitleLabel;
@FXML @FXML private TextField txTextField, bankAccountTypeTextField, holderNameTextField, primaryBankAccountIDTextField,
private TextField txTextField, bankAccountTypeTextField, holderNameTextField, primaryBankAccountIDTextField,
secondaryBankAccountIDTextField; secondaryBankAccountIDTextField;
@FXML @FXML private Button bankTransferInitedButton;
private Button bankTransferInitedButton;
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -136,8 +130,7 @@ public class PendingTradeController extends CachedViewController {
openTradesTable.setItems(tradeItems); openTradesTable.setItems(tradeItems);
openTradesTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); openTradesTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
openTradesTable.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, openTradesTable.getSelectionModel().selectedItemProperty().addListener((obsValue, oldValue, newValue) -> {
newValue) -> {
if (newValue instanceof PendingTradesListItem) { if (newValue instanceof PendingTradesListItem) {
showTradeDetails((PendingTradesListItem) newValue); showTradeDetails((PendingTradesListItem) newValue);
} }
@ -153,10 +146,9 @@ public class PendingTradeController extends CachedViewController {
initCopyIcons(); initCopyIcons();
// select // select
Optional<PendingTradesListItem> currentTradeItemOptional = tradeItems.stream() Optional<PendingTradesListItem> currentTradeItemOptional = tradeItems.stream().filter((e) ->
.filter((e) -> tradeManager.getPendingTrade() != null && e.getTrade().getId().equals(tradeManager tradeManager.getPendingTrade() != null &&
.getPendingTrade().getId())) e.getTrade().getId().equals(tradeManager.getPendingTrade().getId())).findFirst();
.findFirst();
if (currentTradeItemOptional.isPresent()) { if (currentTradeItemOptional.isPresent()) {
openTradesTable.getSelectionModel().select(currentTradeItemOptional.get()); openTradesTable.getSelectionModel().select(currentTradeItemOptional.get());
} }
@ -193,8 +185,8 @@ public class PendingTradeController extends CachedViewController {
private void updateTx(Transaction transaction) { private void updateTx(Transaction transaction) {
txTextField.setText(transaction.getHashAsString()); txTextField.setText(transaction.getHashAsString());
confidenceDisplay = new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, transaction, confidenceDisplay =
progressIndicator); new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, transaction, progressIndicator);
int depthInBlocks = transaction.getConfidence().getDepthInBlocks(); int depthInBlocks = transaction.getConfidence().getDepthInBlocks();
bankTransferInitedButton.setDisable(depthInBlocks == 0); bankTransferInitedButton.setDisable(depthInBlocks == 0);
@ -238,8 +230,8 @@ public class PendingTradeController extends CachedViewController {
currentTrade = trade; currentTrade = trade;
Transaction transaction = trade.getDepositTransaction(); Transaction transaction = trade.getDepositTransaction();
if (transaction == null) { if (transaction == null) {
trade.depositTxChangedProperty().addListener((observableValue, aBoolean, trade.depositTxChangedProperty().addListener((observableValue, aBoolean, aBoolean2) ->
aBoolean2) -> updateTx(trade.getDepositTransaction())); updateTx(trade.getDepositTransaction()));
} else { } else {
updateTx(trade.getDepositTransaction()); updateTx(trade.getDepositTransaction());
} }
@ -260,8 +252,8 @@ public class PendingTradeController extends CachedViewController {
Transaction transaction = trade.getPayoutTransaction(); Transaction transaction = trade.getPayoutTransaction();
confidenceDisplay.destroy(); confidenceDisplay.destroy();
confidenceDisplay = new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, transaction, confidenceDisplay =
progressIndicator); new ConfidenceDisplay(walletFacade.getWallet(), confirmationLabel, transaction, progressIndicator);
txTextField.setText(transaction.getHashAsString()); txTextField.setText(transaction.getHashAsString());
@ -276,8 +268,8 @@ public class PendingTradeController extends CachedViewController {
bankAccountTypeTextField.setText(BitSquareFormatter.formatCoinWithCode(trade.getTradeAmount())); bankAccountTypeTextField.setText(BitSquareFormatter.formatCoinWithCode(trade.getTradeAmount()));
holderNameTextField.setText(BitSquareFormatter.formatVolume(trade.getTradeVolume())); holderNameTextField.setText(BitSquareFormatter.formatVolume(trade.getTradeVolume()));
primaryBankAccountIDTextField.setText(BitSquareFormatter.formatCoinWithCode(FeePolicy.CREATE_OFFER_FEE primaryBankAccountIDTextField.setText(
.add(FeePolicy.TX_FEE))); BitSquareFormatter.formatCoinWithCode(FeePolicy.CREATE_OFFER_FEE.add(FeePolicy.TX_FEE)));
secondaryBankAccountIDTextField.setText(BitSquareFormatter.formatCoinWithCode(trade.getCollateralAmount())); secondaryBankAccountIDTextField.setText(BitSquareFormatter.formatCoinWithCode(trade.getCollateralAmount()));
holderNameCopyIcon.setVisible(false); holderNameCopyIcon.setVisible(false);
@ -339,137 +331,138 @@ public class PendingTradeController extends CachedViewController {
private void setCountryColumnCellFactory() { private void setCountryColumnCellFactory() {
countryColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); countryColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue()));
countryColumn.setCellFactory(new Callback<TableColumn<String, PendingTradesListItem>, TableCell<String, countryColumn.setCellFactory(
PendingTradesListItem>>() { new Callback<TableColumn<String, PendingTradesListItem>, TableCell<String, PendingTradesListItem>>() {
@Override
public TableCell<String, PendingTradesListItem> call(TableColumn<String,
PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
final HBox hBox = new HBox();
{
hBox.setSpacing(3);
hBox.setAlignment(Pos.CENTER);
setGraphic(hBox);
}
@Override @Override
public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) { public TableCell<String, PendingTradesListItem> call(
super.updateItem(tradesTableItem, empty); TableColumn<String, PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
final HBox hBox = new HBox();
hBox.getChildren().clear(); {
if (tradesTableItem != null) { hBox.setSpacing(3);
Country country = tradesTableItem.getTrade().getOffer().getBankAccountCountry(); hBox.setAlignment(Pos.CENTER);
try { setGraphic(hBox);
hBox.getChildren().add(ImageUtil.getIconImageView("/images/countries/" + country
.getCode().toLowerCase() + ".png"));
} catch (Exception e) {
log.warn("Country icon not found: " + "/images/countries/" + country.getCode()
.toLowerCase() + ".png country name: " + country.getName());
} }
Tooltip.install(this, new Tooltip(country.getName()));
} @Override
public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) {
super.updateItem(tradesTableItem, empty);
hBox.getChildren().clear();
if (tradesTableItem != null) {
Country country = tradesTableItem.getTrade().getOffer().getBankAccountCountry();
try {
hBox.getChildren().add(ImageUtil.getIconImageView(
"/images/countries/" + country.getCode().toLowerCase() + ".png"));
} catch (Exception e) {
log.warn("Country icon not found: /images/countries/" +
country.getCode().toLowerCase() + ".png country name: " +
country.getName());
}
Tooltip.install(this, new Tooltip(country.getName()));
}
}
};
} }
}; });
}
});
} }
private void setBankAccountTypeColumnCellFactory() { private void setBankAccountTypeColumnCellFactory() {
bankAccountTypeColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); bankAccountTypeColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue()));
bankAccountTypeColumn.setCellFactory(new Callback<TableColumn<String, PendingTradesListItem>, bankAccountTypeColumn.setCellFactory(
TableCell<String, PendingTradesListItem>>() { new Callback<TableColumn<String, PendingTradesListItem>, TableCell<String, PendingTradesListItem>>() {
@Override
public TableCell<String, PendingTradesListItem> call(TableColumn<String,
PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
@Override @Override
public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) { public TableCell<String, PendingTradesListItem> call(
super.updateItem(tradesTableItem, empty); TableColumn<String, PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
@Override
public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) {
super.updateItem(tradesTableItem, empty);
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 {
setText(""); setText("");
} }
}
};
} }
}; });
}
});
} }
private void setDirectionColumnCellFactory() { private void setDirectionColumnCellFactory() {
directionColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); directionColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue()));
directionColumn.setCellFactory(new Callback<TableColumn<String, PendingTradesListItem>, TableCell<String, directionColumn.setCellFactory(
PendingTradesListItem>>() { new Callback<TableColumn<String, PendingTradesListItem>, TableCell<String, PendingTradesListItem>>() {
@Override
public TableCell<String, PendingTradesListItem> call(TableColumn<String,
PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
final ImageView iconView = new ImageView();
final Button button = new Button();
{
button.setGraphic(iconView);
button.setMinWidth(70);
}
@Override @Override
public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) { public TableCell<String, PendingTradesListItem> call(
super.updateItem(tradesTableItem, empty); TableColumn<String, PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
final ImageView iconView = new ImageView();
final Button button = new Button();
if (tradesTableItem != null) { {
String title; button.setGraphic(iconView);
Image icon; button.setMinWidth(70);
Offer offer = tradesTableItem.getTrade().getOffer();
if (offer.getDirection() == Direction.SELL) {
icon = buyIcon;
title = BitSquareFormatter.formatDirection(Direction.BUY, true);
} else {
icon = sellIcon;
title = BitSquareFormatter.formatDirection(Direction.SELL, true);
} }
button.setDisable(true);
iconView.setImage(icon); @Override
button.setText(title); public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) {
setGraphic(button); super.updateItem(tradesTableItem, empty);
} else {
setGraphic(null); if (tradesTableItem != null) {
} String title;
Image icon;
Offer offer = tradesTableItem.getTrade().getOffer();
if (offer.getDirection() == Direction.SELL) {
icon = buyIcon;
title = BitSquareFormatter.formatDirection(Direction.BUY, true);
} else {
icon = sellIcon;
title = BitSquareFormatter.formatDirection(Direction.SELL, true);
}
button.setDisable(true);
iconView.setImage(icon);
button.setText(title);
setGraphic(button);
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
private void setSelectColumnCellFactory() { private void setSelectColumnCellFactory() {
selectColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); selectColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue()));
selectColumn.setCellFactory(new Callback<TableColumn<String, PendingTradesListItem>, TableCell<String, selectColumn.setCellFactory(
PendingTradesListItem>>() { new Callback<TableColumn<String, PendingTradesListItem>, TableCell<String, PendingTradesListItem>>() {
@Override
public TableCell<String, PendingTradesListItem> call(TableColumn<String,
PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
final Button button = new Button("Select");
@Override @Override
public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) { public TableCell<String, PendingTradesListItem> call(
super.updateItem(tradesTableItem, empty); TableColumn<String, PendingTradesListItem> directionColumn) {
return new TableCell<String, PendingTradesListItem>() {
final Button button = new Button("Select");
if (tradesTableItem != null) { @Override
button.setOnAction(event -> showTradeDetails(tradesTableItem)); public void updateItem(final PendingTradesListItem tradesTableItem, boolean empty) {
setGraphic(button); super.updateItem(tradesTableItem, empty);
} else {
setGraphic(null); if (tradesTableItem != null) {
} button.setOnAction(event -> showTradeDetails(tradesTableItem));
setGraphic(button);
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
} }

View file

@ -252,8 +252,8 @@ public class SettingsController extends CachedViewController {
public void onSelectBankAccountRegion() { public void onSelectBankAccountRegion() {
bankAccountCountryComboBox.setVisible(true); bankAccountCountryComboBox.setVisible(true);
Region selectedBankAccountRegion = bankAccountRegionComboBox.getSelectionModel().getSelectedItem(); Region selectedBankAccountRegion = bankAccountRegionComboBox.getSelectionModel().getSelectedItem();
bankAccountCountryComboBox.setItems(FXCollections.observableArrayList(CountryUtil.getAllCountriesFor bankAccountCountryComboBox.setItems(
(selectedBankAccountRegion))); FXCollections.observableArrayList(CountryUtil.getAllCountriesFor(selectedBankAccountRegion)));
} }
@FXML @FXML
@ -522,8 +522,8 @@ public class SettingsController extends CachedViewController {
bankAccountCurrencyComboBox.getSelectionModel().selectFirst(); bankAccountCurrencyComboBox.getSelectionModel().selectFirst();
bankAccountRegionComboBox.getSelectionModel().select(3); bankAccountRegionComboBox.getSelectionModel().select(3);
Optional<Country> country = bankAccountCountryComboBox.getItems().stream().filter(e -> e.getCode().equals Optional<Country> country = bankAccountCountryComboBox.getItems().stream().filter(e ->
(CountryUtil.getDefaultCountry().getCode())).findFirst(); e.getCode().equals(CountryUtil.getDefaultCountry().getCode())).findFirst();
if (country.isPresent()) if (country.isPresent())
bankAccountCountryComboBox.getSelectionModel().select(country.get()); bankAccountCountryComboBox.getSelectionModel().select(country.get());
@ -703,7 +703,8 @@ public class SettingsController extends CachedViewController {
private boolean verifyBankAccountData() { private boolean verifyBankAccountData() {
try { try {
BitSquareValidator.textFieldsNotEmptyWithReset(bankAccountTitleTextField, bankAccountHolderNameTextField, BitSquareValidator.textFieldsNotEmptyWithReset(
bankAccountTitleTextField, bankAccountHolderNameTextField,
bankAccountPrimaryIDTextField, bankAccountSecondaryIDTextField); bankAccountPrimaryIDTextField, bankAccountSecondaryIDTextField);
BankAccountType bankAccountTypeInfo = bankAccountTypesComboBox.getSelectionModel().getSelectedItem(); BankAccountType bankAccountTypeInfo = bankAccountTypesComboBox.getSelectionModel().getSelectedItem();
@ -712,10 +713,8 @@ public class SettingsController extends CachedViewController {
bankAccountTypeInfo); bankAccountTypeInfo);
return bankAccountTypesComboBox.getSelectionModel().getSelectedItem() != null && return bankAccountTypesComboBox.getSelectionModel().getSelectedItem() != null &&
bankAccountCountryComboBox.getSelectionModel() bankAccountCountryComboBox.getSelectionModel().getSelectedItem() != null &&
.getSelectedItem() != null && bankAccountCurrencyComboBox.getSelectionModel() bankAccountCurrencyComboBox.getSelectionModel().getSelectedItem() != null;
.getSelectedItem() !=
null;
} catch (BitSquareValidator.ValidationException e) { } catch (BitSquareValidator.ValidationException e) {
return false; return false;
} }
@ -762,6 +761,5 @@ public class SettingsController extends CachedViewController {
} }
} }
} }

View file

@ -73,8 +73,8 @@ 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) -> Platform ((TabPane) root).getSelectionModel().selectedIndexProperty().addListener((observableValue) ->
.runLater(() -> ValidatingTextField.hidePopover())); Platform.runLater(() -> ValidatingTextField.hidePopover()));
} }
@ -88,8 +88,8 @@ public class TradeController extends CachedViewController {
if (navigationItem == NavigationItem.ORDER_BOOK) { if (navigationItem == NavigationItem.ORDER_BOOK) {
checkArgument(orderBookLoader == null); checkArgument(orderBookLoader == null);
// Orderbook must not be cached by GuiceFXMLLoader as we use 2 instances for sell and buy screens. // Orderbook must not be cached by GuiceFXMLLoader as we use 2 instances for sell and buy screens.
orderBookLoader = new GuiceFXMLLoader(getClass().getResource(NavigationItem.ORDER_BOOK.getFxmlUrl()), orderBookLoader =
false); new GuiceFXMLLoader(getClass().getResource(NavigationItem.ORDER_BOOK.getFxmlUrl()), false);
try { try {
final Parent view = orderBookLoader.load(); final Parent view = orderBookLoader.load();
final Tab tab = new Tab("Orderbook"); final Tab tab = new Tab("Orderbook");

View file

@ -107,8 +107,8 @@ public class CreateOfferController extends CachedViewController {
viewModel.bankAccountCounty.set(bankAccount.getCountry().getName()); viewModel.bankAccountCounty.set(bankAccount.getCountry().getName());
} }
viewModel.acceptedCountries.set(BitSquareFormatter.countryLocalesToString(settings.getAcceptedCountries())); viewModel.acceptedCountries.set(BitSquareFormatter.countryLocalesToString(settings.getAcceptedCountries()));
viewModel.acceptedLanguages.set(BitSquareFormatter.languageLocalesToString(settings viewModel.acceptedLanguages.set(
.getAcceptedLanguageLocales())); BitSquareFormatter.languageLocalesToString(settings.getAcceptedLanguageLocales()));
viewModel.feeLabel.set(BitSquareFormatter.formatCoinWithCode(FeePolicy.CREATE_OFFER_FEE.add(FeePolicy.TX_FEE))); viewModel.feeLabel.set(BitSquareFormatter.formatCoinWithCode(FeePolicy.CREATE_OFFER_FEE.add(FeePolicy.TX_FEE)));
offerId = UUID.randomUUID().toString(); offerId = UUID.randomUUID().toString();
@ -221,8 +221,8 @@ public class CreateOfferController extends CachedViewController {
double price = BitSquareFormatter.parseToDouble(viewModel.price.get()); double price = BitSquareFormatter.parseToDouble(viewModel.price.get());
double volume = amount * price; double volume = amount * price;
viewModel.volume.set(BitSquareFormatter.formatVolume(volume)); viewModel.volume.set(BitSquareFormatter.formatVolume(volume));
viewModel.totals.set(BitSquareFormatter.formatTotalsAsBtc(viewModel.amount.get(), collateral, viewModel.totals.set(BitSquareFormatter.formatTotalsAsBtc(
FeePolicy.CREATE_OFFER_FEE.add(FeePolicy.TX_FEE))); viewModel.amount.get(), collateral, FeePolicy.CREATE_OFFER_FEE.add(FeePolicy.TX_FEE)));
viewModel.collateral.set(BitSquareFormatter.formatCollateralAsBtc(viewModel.amount.get(), collateral)); viewModel.collateral.set(BitSquareFormatter.formatCollateralAsBtc(viewModel.amount.get(), collateral));
}); });

View file

@ -332,8 +332,8 @@ public class OrderBookController extends CachedViewController {
private void takeOffer(Offer offer) { private void takeOffer(Offer offer) {
if (isRegistered()) { if (isRegistered()) {
TakerOfferController takerOfferController = (TakerOfferController) parentController TakerOfferController takerOfferController =
.loadViewAndGetChildController(NavigationItem.TAKE_OFFER); (TakerOfferController) parentController.loadViewAndGetChildController(NavigationItem.TAKE_OFFER);
Coin requestedAmount; Coin requestedAmount;
if (!"".equals(amount.getText())) { if (!"".equals(amount.getText())) {
@ -357,8 +357,8 @@ public class OrderBookController extends CachedViewController {
private void applyOffers() { private void applyOffers() {
orderBook.applyFilter(orderBookFilter); orderBook.applyFilter(orderBookFilter);
priceColumn.setSortType((orderBookFilter.getDirection() == Direction.BUY) ? TableColumn.SortType.ASCENDING : priceColumn.setSortType((orderBookFilter.getDirection() == Direction.BUY) ?
TableColumn.SortType.DESCENDING); TableColumn.SortType.ASCENDING : TableColumn.SortType.DESCENDING);
orderBookTable.sort(); orderBookTable.sort();
if (orderBookTable.getItems() != null) { if (orderBookTable.getItems() != null) {
@ -386,120 +386,124 @@ public class OrderBookController extends CachedViewController {
private void setDirectionColumnCellFactory() { private void setDirectionColumnCellFactory() {
directionColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); directionColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue()));
directionColumn.setCellFactory(new Callback<TableColumn<String, OrderBookListItem>, TableCell<String, directionColumn.setCellFactory(
OrderBookListItem>>() { new Callback<TableColumn<String, OrderBookListItem>, TableCell<String, OrderBookListItem>>() {
@Override
public TableCell<String, OrderBookListItem> call(TableColumn<String, OrderBookListItem> directionColumn) {
return new TableCell<String, OrderBookListItem>() {
final ImageView iconView = new ImageView();
final Button button = new Button();
{
button.setGraphic(iconView);
button.setMinWidth(70);
}
@Override @Override
public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) { public TableCell<String, OrderBookListItem> call(
super.updateItem(orderBookListItem, empty); TableColumn<String, OrderBookListItem> directionColumn) {
return new TableCell<String, OrderBookListItem>() {
final ImageView iconView = new ImageView();
final Button button = new Button();
if (orderBookListItem != null) { {
String title; button.setGraphic(iconView);
Image icon; button.setMinWidth(70);
Offer offer = orderBookListItem.getOffer();
if (offer.getMessagePublicKey().equals(user.getMessagePublicKey())) {
icon = ImageUtil.getIconImage(ImageUtil.REMOVE);
title = "Remove";
button.setOnAction(event -> removeOffer(orderBookListItem.getOffer()));
} else {
if (offer.getDirection() == Direction.SELL) {
icon = buyIcon;
title = BitSquareFormatter.formatDirection(Direction.BUY, true);
} else {
icon = sellIcon;
title = BitSquareFormatter.formatDirection(Direction.SELL, true);
}
button.setDefaultButton(getIndex() == 0);
button.setOnAction(event -> takeOffer(orderBookListItem.getOffer()));
} }
@Override
public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) {
super.updateItem(orderBookListItem, empty);
iconView.setImage(icon); if (orderBookListItem != null) {
button.setText(title); String title;
setGraphic(button); Image icon;
} else { Offer offer = orderBookListItem.getOffer();
setGraphic(null);
} if (offer.getMessagePublicKey().equals(user.getMessagePublicKey())) {
icon = ImageUtil.getIconImage(ImageUtil.REMOVE);
title = "Remove";
button.setOnAction(event -> removeOffer(orderBookListItem.getOffer()));
} else {
if (offer.getDirection() == Direction.SELL) {
icon = buyIcon;
title = BitSquareFormatter.formatDirection(Direction.BUY, true);
} else {
icon = sellIcon;
title = BitSquareFormatter.formatDirection(Direction.SELL, true);
}
button.setDefaultButton(getIndex() == 0);
button.setOnAction(event -> takeOffer(orderBookListItem.getOffer()));
}
iconView.setImage(icon);
button.setText(title);
setGraphic(button);
} else {
setGraphic(null);
}
}
};
} }
}; });
}
});
} }
private void setCountryColumnCellFactory() { private void setCountryColumnCellFactory() {
countryColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); countryColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue()));
countryColumn.setCellFactory(new Callback<TableColumn<String, OrderBookListItem>, TableCell<String, countryColumn.setCellFactory(
OrderBookListItem>>() { new Callback<TableColumn<String, OrderBookListItem>, TableCell<String, OrderBookListItem>>() {
@Override
public TableCell<String, OrderBookListItem> call(TableColumn<String, OrderBookListItem> directionColumn) {
return new TableCell<String, OrderBookListItem>() {
final HBox hBox = new HBox();
{
hBox.setSpacing(3);
hBox.setAlignment(Pos.CENTER);
setGraphic(hBox);
}
@Override @Override
public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) { public TableCell<String, OrderBookListItem> call(
super.updateItem(orderBookListItem, empty); TableColumn<String, OrderBookListItem> directionColumn) {
return new TableCell<String, OrderBookListItem>() {
final HBox hBox = new HBox();
hBox.getChildren().clear(); {
if (orderBookListItem != null) { hBox.setSpacing(3);
Country country = orderBookListItem.getOffer().getBankAccountCountry(); hBox.setAlignment(Pos.CENTER);
try { setGraphic(hBox);
hBox.getChildren().add(ImageUtil.getIconImageView("/images/countries/" + country
.getCode().toLowerCase() + ".png"));
} catch (Exception e) {
log.warn("Country icon not found: " + "/images/countries/" + country.getCode()
.toLowerCase() + ".png country name: " + country.getName());
} }
Tooltip.install(this, new Tooltip(country.getName()));
} @Override
public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) {
super.updateItem(orderBookListItem, empty);
hBox.getChildren().clear();
if (orderBookListItem != null) {
Country country = orderBookListItem.getOffer().getBankAccountCountry();
try {
hBox.getChildren().add(ImageUtil.getIconImageView(
"/images/countries/" + country.getCode().toLowerCase() + ".png"));
} catch (Exception e) {
log.warn("Country icon not found: /images/countries/" +
country.getCode().toLowerCase() + ".png country name: " +
country.getName());
}
Tooltip.install(this, new Tooltip(country.getName()));
}
}
};
} }
}; });
}
});
} }
private void setBankAccountTypeColumnCellFactory() { private void setBankAccountTypeColumnCellFactory() {
bankAccountTypeColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue())); bankAccountTypeColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper(offer.getValue()));
bankAccountTypeColumn.setCellFactory(new Callback<TableColumn<String, OrderBookListItem>, TableCell<String, bankAccountTypeColumn.setCellFactory(
OrderBookListItem>>() { new Callback<TableColumn<String, OrderBookListItem>, TableCell<String, OrderBookListItem>>() {
@Override
public TableCell<String, OrderBookListItem> call(TableColumn<String, OrderBookListItem> directionColumn) {
return new TableCell<String, OrderBookListItem>() {
@Override @Override
public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) { public TableCell<String, OrderBookListItem> call(
super.updateItem(orderBookListItem, empty); TableColumn<String, OrderBookListItem> directionColumn) {
return new TableCell<String, OrderBookListItem>() {
@Override
public void updateItem(final OrderBookListItem orderBookListItem, boolean empty) {
super.updateItem(orderBookListItem, empty);
if (orderBookListItem != null) { if (orderBookListItem != null) {
BankAccountType bankAccountType = orderBookListItem.getOffer().getBankAccountType(); BankAccountType bankAccountType = orderBookListItem.getOffer().getBankAccountType();
setText(Localisation.get(bankAccountType.toString())); setText(Localisation.get(bankAccountType.toString()));
} else { } else {
setText(""); setText("");
} }
}
};
} }
}; });
}
});
} }

View file

@ -34,10 +34,10 @@ public class OrderBookListItem {
public OrderBookListItem(Offer offer) { public OrderBookListItem(Offer offer) {
this.offer = offer; this.offer = offer;
this.price.set(BitSquareFormatter.formatPrice(offer.getPrice())); this.price.set(BitSquareFormatter.formatPrice(offer.getPrice()));
this.amount.set(BitSquareFormatter.formatCoin(offer.getAmount()) + " (" + BitSquareFormatter.formatCoin(offer this.amount.set(BitSquareFormatter.formatCoin(
.getMinAmount()) + ")"); offer.getAmount()) + " (" + BitSquareFormatter.formatCoin(offer.getMinAmount()) + ")");
this.volume.set(BitSquareFormatter.formatVolumeWithMinVolume(offer.getOfferVolume(), this.volume.set(BitSquareFormatter.formatVolumeWithMinVolume(
offer.getMinOfferVolume())); offer.getOfferVolume(), offer.getMinOfferVolume()));
} }

View file

@ -56,22 +56,16 @@ public class TakerOfferController extends CachedViewController {
private String tradeId; private String tradeId;
private String depositTxId; private String depositTxId;
@FXML @FXML private Accordion accordion;
private Accordion accordion; @FXML private TitledPane takeOfferTitledPane, waitBankTxTitledPane, summaryTitledPane;
@FXML @FXML private ValidatedTextField amountTextField;
private TitledPane takeOfferTitledPane, waitBankTxTitledPane, summaryTitledPane; @FXML private TextField priceTextField, volumeTextField, collateralTextField, feeTextField, totalTextField,
@FXML
private ValidatedTextField amountTextField;
@FXML
private TextField priceTextField, volumeTextField, collateralTextField, feeTextField, totalTextField,
bankAccountTypeTextField, countryTextField, arbitratorsTextField, bankAccountTypeTextField, countryTextField, arbitratorsTextField,
supportedLanguagesTextField, supportedCountriesTextField, depositTxIdTextField, summaryPaidTextField, supportedLanguagesTextField, supportedCountriesTextField, depositTxIdTextField, summaryPaidTextField,
summaryReceivedTextField, summaryFeesTextField, summaryCollateralTextField, summaryReceivedTextField, summaryFeesTextField, summaryCollateralTextField,
summaryDepositTxIdTextField, summaryPayoutTxIdTextField; summaryDepositTxIdTextField, summaryPayoutTxIdTextField;
@FXML @FXML private Label infoLabel, headLineLabel, collateralLabel;
private Label infoLabel, headLineLabel, collateralLabel; @FXML private Button takeOfferButton, receivedFiatButton;
@FXML
private Button takeOfferButton, receivedFiatButton;
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Constructor // Constructor
@ -122,8 +116,8 @@ public class TakerOfferController extends CachedViewController {
public void applyData() { public void applyData() {
amountTextField.setText(requestedAmount.toPlainString()); amountTextField.setText(requestedAmount.toPlainString());
amountTextField.setPromptText(BitSquareFormatter.formatCoinWithCode(offer.getMinAmount()) + " - " + amountTextField.setPromptText(BitSquareFormatter.formatCoinWithCode(
BitSquareFormatter.formatCoinWithCode(offer.getAmount())); offer.getMinAmount()) + " - " + BitSquareFormatter.formatCoinWithCode(offer.getAmount()));
priceTextField.setText(BitSquareFormatter.formatPrice(offer.getPrice())); priceTextField.setText(BitSquareFormatter.formatPrice(offer.getPrice()));
applyVolume(); applyVolume();
collateralLabel.setText("Collateral (" + getCollateralAsPercent() + "):"); collateralLabel.setText("Collateral (" + getCollateralAsPercent() + "):");
@ -138,8 +132,8 @@ public class TakerOfferController extends CachedViewController {
//todo list //todo list
// arbitratorsTextField.setText(offer.getArbitrator().getName()); // arbitratorsTextField.setText(offer.getArbitrator().getName());
supportedLanguagesTextField.setText(BitSquareFormatter.languageLocalesToString(offer supportedLanguagesTextField.setText(BitSquareFormatter.languageLocalesToString(
.getAcceptedLanguageLocales())); offer.getAcceptedLanguageLocales()));
supportedCountriesTextField.setText(BitSquareFormatter.countryLocalesToString(offer.getAcceptedCountries())); supportedCountriesTextField.setText(BitSquareFormatter.countryLocalesToString(offer.getAcceptedCountries()));
amountTextField.textProperty().addListener(e -> { amountTextField.textProperty().addListener(e -> {
@ -162,14 +156,14 @@ public class TakerOfferController extends CachedViewController {
if (amountTextField.isInvalid()) { if (amountTextField.isInvalid()) {
Popups.openErrorPopup("Invalid input", "The requested amount you entered is not a valid amount."); Popups.openErrorPopup("Invalid input", "The requested amount you entered is not a valid amount.");
} else if (BitSquareValidator.tradeAmountOutOfRange(amount, offer)) { } else if (BitSquareValidator.tradeAmountOutOfRange(amount, offer)) {
Popups.openErrorPopup("Invalid input", "The requested amount you entered is outside of the range of the " + Popups.openErrorPopup(
"offered amount."); "Invalid input", "The requested amount you entered is outside of the range of the offered amount.");
} else if (addressEntry == null || getTotal().compareTo(walletFacade.getBalanceForAddress(addressEntry } else if (addressEntry == null ||
.getAddress())) > 0) { getTotal().compareTo(walletFacade.getBalanceForAddress(addressEntry.getAddress())) > 0) {
Popups.openErrorPopup("Insufficient money", "You don't have enough funds for that trade."); Popups.openErrorPopup("Insufficient money", "You don't have enough funds for that trade.");
} else if (tradeManager.isOfferAlreadyInTrades(offer)) { } else if (tradeManager.isOfferAlreadyInTrades(offer)) {
Popups.openErrorPopup("Offer previously accepted", "You have that offer already taken. Open the offer " + Popups.openErrorPopup("Offer previously accepted",
"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);
amountTextField.setEditable(false); amountTextField.setEditable(false);
@ -198,10 +192,10 @@ public class TakerOfferController extends CachedViewController {
summaryPaidTextField.setText(BitSquareFormatter.formatCoinWithCode(trade.getTradeAmount())); summaryPaidTextField.setText(BitSquareFormatter.formatCoinWithCode(trade.getTradeAmount()));
summaryReceivedTextField.setText(BitSquareFormatter.formatVolume(trade.getTradeVolume())); summaryReceivedTextField.setText(BitSquareFormatter.formatVolume(trade.getTradeVolume()));
summaryFeesTextField.setText(BitSquareFormatter.formatCoinWithCode(FeePolicy.TAKE_OFFER_FEE.add summaryFeesTextField.setText(BitSquareFormatter.formatCoinWithCode(
(FeePolicy.TX_FEE))); FeePolicy.TAKE_OFFER_FEE.add(FeePolicy.TX_FEE)));
summaryCollateralTextField.setText(BitSquareFormatter.formatCoinWithCode(trade summaryCollateralTextField.setText(BitSquareFormatter.formatCoinWithCode(
.getCollateralAmount())); trade.getCollateralAmount()));
summaryDepositTxIdTextField.setText(depositTxId); summaryDepositTxIdTextField.setText(depositTxId);
summaryPayoutTxIdTextField.setText(payoutTxId); summaryPayoutTxIdTextField.setText(payoutTxId);
} }
@ -209,8 +203,8 @@ public class TakerOfferController extends CachedViewController {
@Override @Override
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", "Error while executing trade process" + Popups.openErrorPopup("Error while executing trade process",
" at state: " + state + " / " + throwable); "Error while executing trade process at state: " + state + " / " + throwable);
} }
@Override @Override

View file

@ -78,8 +78,10 @@ public class BtcValidator extends NumberValidator {
BigDecimal bd = new BigDecimal(input); BigDecimal bd = new BigDecimal(input);
final BigDecimal satoshis = bd.movePointRight(8); final BigDecimal satoshis = bd.movePointRight(8);
if (satoshis.scale() > 0) if (satoshis.scale() > 0)
return new ValidationResult(false, "Input results in a Bitcoin value with a fraction of the smallest unit" + return new ValidationResult(
" (Satoshi).", ErrorType.FRACTIONAL_SATOSHI); false,
"Input results in a Bitcoin value with a fraction of the smallest unit (Satoshi).",
ErrorType.FRACTIONAL_SATOSHI);
else else
return new ValidationResult(true); return new ValidationResult(true);
} }
@ -88,7 +90,9 @@ public class BtcValidator extends NumberValidator {
BigDecimal bd = new BigDecimal(input); BigDecimal bd = new BigDecimal(input);
final BigDecimal satoshis = bd.movePointRight(8); final BigDecimal satoshis = bd.movePointRight(8);
if (satoshis.longValue() > NetworkParameters.MAX_MONEY.longValue()) if (satoshis.longValue() > NetworkParameters.MAX_MONEY.longValue())
return new ValidationResult(false, "Input larger as maximum possible Bitcoin value is not allowed.", return new ValidationResult(
false,
"Input larger as maximum possible Bitcoin value is not allowed.",
ErrorType.EXCEEDS_MAX_BTC_VALUE); ErrorType.EXCEEDS_MAX_BTC_VALUE);
else else
return new ValidationResult(true); return new ValidationResult(true);

View file

@ -186,8 +186,8 @@ public class ConfidenceDisplay {
latestTransaction = transaction; latestTransaction = transaction;
} }
} }
if (latestTransaction != null && (transaction == null || latestTransaction.getHashAsString().equals if (latestTransaction != null && (transaction == null ||
(transaction.getHashAsString()))) { latestTransaction.getHashAsString().equals(transaction.getHashAsString()))) {
updateConfidence(latestTransaction); updateConfidence(latestTransaction);
} }
} }

View file

@ -63,7 +63,9 @@ public class FiatValidator extends NumberValidator {
protected ValidationResult validateIfNotExceedsMinFiatValue(String input) { protected ValidationResult validateIfNotExceedsMinFiatValue(String input) {
double d = Double.parseDouble(input); double d = Double.parseDouble(input);
if (d < MIN_FIAT_VALUE) if (d < MIN_FIAT_VALUE)
return new ValidationResult(false, "Input smaller as minimum possible Fiat value is not allowed..", return new ValidationResult(
false,
"Input smaller as minimum possible Fiat value is not allowed..",
ErrorType.UNDERCUT_MIN_FIAT_VALUE); ErrorType.UNDERCUT_MIN_FIAT_VALUE);
else else
return new ValidationResult(true); return new ValidationResult(true);
@ -72,7 +74,9 @@ public class FiatValidator extends NumberValidator {
protected ValidationResult validateIfNotExceedsMaxFiatValue(String input) { protected ValidationResult validateIfNotExceedsMaxFiatValue(String input) {
double d = Double.parseDouble(input); double d = Double.parseDouble(input);
if (d > MAX_FIAT_VALUE) if (d > MAX_FIAT_VALUE)
return new ValidationResult(false, "Input larger as maximum possible Fiat value is not allowed.", return new ValidationResult(
false,
"Input larger as maximum possible Fiat value is not allowed.",
ErrorType.EXCEEDS_MAX_FIAT_VALUE); ErrorType.EXCEEDS_MAX_FIAT_VALUE);
else else
return new ValidationResult(true); return new ValidationResult(true);

View file

@ -55,8 +55,8 @@ public class ValidationHelper {
minAmountTextField.focusedProperty().addListener((ov, oldValue, newValue) -> { minAmountTextField.focusedProperty().addListener((ov, oldValue, newValue) -> {
// only on focus out and ignore focus loss from window // only on focus out and ignore focus loss from window
if (!newValue && minAmountTextField.getScene() != null && minAmountTextField.getScene().getWindow() if (!newValue && minAmountTextField.getScene() != null &&
.isFocused()) minAmountTextField.getScene().getWindow().isFocused())
validateMinAmount(amountTextField, validateMinAmount(amountTextField,
minAmountTextField, minAmountTextField,
amount, amount,

View file

@ -25,23 +25,24 @@ import java.util.stream.Collectors;
public class CountryUtil { public class CountryUtil {
private static final String[] countryCodes = new String[]{"AE", "AL", "AR", "AT", "AU", "BA", "BE", "BG", "BH", private static final String[] countryCodes = new String[]{"AE", "AL", "AR", "AT", "AU", "BA", "BE", "BG", "BH",
"BO", "BR", "BY", "CA", "CH", "CL", "CN", "CO", "CR", "CS", "CU", "CY", "CZ", "BO", "BR", "BY", "CA", "CH", "CL", "CN", "CO", "CR", "CS", "CU", "CY", "CZ", "DE", "DK", "DO", "DZ",
"DE", "DK", "DO", "DZ", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HR", "HU", "EC", "EE", "EG", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HR", "HU", "ID", "IE", "IL", "IN",
"ID", "IE", "IL", "IN", "IQ", "IS", "IT", "JO", "JP", "KR", "KW", "LB", "LT", "LU", "IQ", "IS", "IT", "JO", "JP", "KR", "KW", "LB", "LT", "LU", "LV", "LY", "MA", "ME", "MK", "MT", "MX",
"LV", "LY", "MA", "ME", "MK", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "MY", "NI", "NL", "NO", "NZ", "OM", "PA", "PE", "PH", "PL", "PR", "PT", "PY", "QA", "RO", "RS", "RU",
"PR", "PT", "PY", "QA", "RO", "RS", "RU", "SA", "SD", "SE", "SG", "SI", "SK", "SV", "SA", "SD", "SE", "SG", "SI", "SK", "SV", "SY", "TH", "TN", "TR", "TW", "UA", "US", "UY", "VE", "VN",
"SY", "TH", "TN", "TR", "TW", "UA", "US", "UY", "VE", "VN", "YE", "ZA"}; "YE", "ZA"};
private static final List<String> countryCodeList = Arrays.asList(countryCodes); private static final List<String> countryCodeList = Arrays.asList(countryCodes);
private static final String[] regionCodes = new String[]{"AS", "EU", "SA", "EU", "OC", "EU", "EU", "EU", "AS", private static final String[] regionCodes = new String[]{"AS", "EU", "SA", "EU", "OC", "EU", "EU", "EU", "AS",
"SA", "SA", "EU", "NA", "EU", "SA", "AS", "SA", "NA", "EU", "NA", "AS", "EU", "SA", "SA", "EU", "NA", "EU", "SA", "AS", "SA", "NA", "EU", "NA", "AS", "EU", "EU", "EU", "NA", "AF",
"EU", "EU", "NA", "AF", "SA", "EU", "AF", "EU", "EU", "EU", "EU", "EU", "NA", "AS", "NA", "EU", "EU", "SA", "EU", "AF", "EU", "EU", "EU", "EU", "EU", "NA", "AS", "NA", "EU", "EU", "AS", "EU", "AS", "AS",
"AS", "EU", "AS", "AS", "AS", "EU", "EU", "AS", "AS", "AS", "AS", "AS", "EU", "EU", "AS", "EU", "EU", "AS", "AS", "AS", "AS", "AS", "EU", "EU", "EU", "AF", "AF", "EU", "EU", "EU", "NA",
"EU", "AF", "AF", "EU", "EU", "EU", "NA", "AS", "NA", "EU", "EU", "OC", "AS", "NA", "SA", "AS", "EU", "AS", "NA", "EU", "EU", "OC", "AS", "NA", "SA", "AS", "EU", "NA", "EU", "SA", "AS", "EU", "EU", "EU",
"NA", "EU", "SA", "AS", "EU", "EU", "EU", "AS", "AF", "EU", "AS", "EU", "EU", "NA", "AS", "AF", "EU", "AS", "EU", "EU", "NA", "AS", "AS", "AF", "AS", "AS", "EU", "NA", "SA", "SA", "AS",
"AS", "AS", "AF", "AS", "AS", "EU", "NA", "SA", "SA", "AS", "AS", "AF"}; "AS", "AF"};
private static final List<String> regionCodeList = Arrays.asList(regionCodes); private static final List<String> regionCodeList = Arrays.asList(regionCodes);
private static final String[][] regionCodeToName = new String[][]{{"NA", "North America"}, {"SA", private static final String[][] regionCodeToName = new String[][]{
"South America"}, {"AF", "Africa"}, {"EU", "Europe"}, {"AS", "Asia"}, {"OC", "Oceania"}}; {"NA", "North America"}, {"SA", "South America"}, {"AF", "Africa"}, {"EU", "Europe"}, {"AS", "Asia"},
{"OC", "Oceania"}};
public static List<Region> getAllRegions() { public static List<Region> getAllRegions() {
@ -75,8 +76,8 @@ public class CountryUtil {
} }
public static List<Country> getAllCountriesFor(Region selectedRegion) { public static List<Country> getAllCountriesFor(Region selectedRegion) {
return Lists.newArrayList(Collections2.filter(getAllCountries(), country -> selectedRegion != null && country return Lists.newArrayList(Collections2.filter(getAllCountries(), country ->
!= null && selectedRegion.equals(country.getRegion()))); selectedRegion != null && country != null && selectedRegion.equals(country.getRegion())));
} }
@ -112,8 +113,9 @@ public class CountryUtil {
private static List<Locale> getAllCountryLocales() { private static List<Locale> getAllCountryLocales() {
List<Locale> allLocales = Arrays.asList(Locale.getAvailableLocales()); List<Locale> allLocales = Arrays.asList(Locale.getAvailableLocales());
Set<Locale> allLocalesAsSet = allLocales.stream().filter(locale -> !"".equals(locale.getCountry())).map Set<Locale> allLocalesAsSet =
(locale -> new Locale("", locale.getCountry(), "")).collect(Collectors.toSet()); allLocales.stream().filter(locale -> !"".equals(locale.getCountry())).map(locale ->
new Locale("", locale.getCountry(), "")).collect(Collectors.toSet());
/* /*
same as: same as:
Set<Locale> allLocalesAsSet = new HashSet<>(); Set<Locale> allLocalesAsSet = new HashSet<>();

View file

@ -41,8 +41,9 @@ public class LanguageUtil {
public static List<Locale> getAllLanguageLocales() { public static List<Locale> getAllLanguageLocales() {
List<Locale> allLocales = Arrays.asList(Locale.getAvailableLocales()); List<Locale> allLocales = Arrays.asList(Locale.getAvailableLocales());
final Set<Locale> allLocalesAsSet = allLocales.stream().filter(locale -> !"".equals(locale.getLanguage())) final Set<Locale> allLocalesAsSet =
.map(locale -> new Locale(locale.getLanguage(), "")).collect(Collectors.toSet()); allLocales.stream().filter(locale -> !"".equals(locale.getLanguage())).map(locale ->
new Locale(locale.getLanguage(), "")).collect(Collectors.toSet());
allLocales = new ArrayList<>(); allLocales = new ArrayList<>();
allLocales.addAll(allLocalesAsSet); allLocales.addAll(allLocalesAsSet);
allLocales.sort((locale1, locale2) -> locale1.getDisplayLanguage().compareTo(locale2.getDisplayLanguage())); allLocales.sort((locale1, locale2) -> locale1.getDisplayLanguage().compareTo(locale2.getDisplayLanguage()));

View file

@ -57,8 +57,8 @@ public class Localisation {
class UTF8Control extends ResourceBundle.Control { class UTF8Control extends ResourceBundle.Control {
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
boolean reload) throws IllegalAccessException, InstantiationException, IOException { throws IllegalAccessException, InstantiationException, IOException {
// The below is a copy of the default implementation. // The below is a copy of the default implementation.
final String bundleName = toBundleName(baseName, locale); final String bundleName = toBundleName(baseName, locale);
final String resourceName = toResourceName(bundleName, "properties"); final String resourceName = toResourceName(bundleName, "properties");

View file

@ -53,6 +53,8 @@ import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.bitsquare.msg.SeedNodeAddress.StaticSeedNodeAddresses;
/** /**
* Creates a DHT peer and bootstrap to a seed node * Creates a DHT peer and bootstrap to a seed node
*/ */
@ -73,8 +75,8 @@ public class BootstrappedPeerFactory {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Inject @Inject
public BootstrappedPeerFactory(Persistence persistence, @Named("defaultSeedNode") SeedNodeAddress public BootstrappedPeerFactory(Persistence persistence,
.StaticSeedNodeAddresses defaultStaticSeedNodeAddresses) { @Named("defaultSeedNode") StaticSeedNodeAddresses defaultStaticSeedNodeAddresses) {
this.persistence = persistence; this.persistence = persistence;
this.seedNodeAddress = new SeedNodeAddress(defaultStaticSeedNodeAddresses); this.seedNodeAddress = new SeedNodeAddress(defaultStaticSeedNodeAddresses);
} }
@ -154,8 +156,8 @@ public class BootstrappedPeerFactory {
bootstrapWithRelay(peerDHT, nodeBehindNat); bootstrapWithRelay(peerDHT, nodeBehindNat);
break; break;
case "startPortForwarding": case "startPortForwarding":
FutureDiscover futureDiscover = peerDHT.peer().discover().peerAddress(getBootstrapAddress()) FutureDiscover futureDiscover =
.start(); peerDHT.peer().discover().peerAddress(getBootstrapAddress()).start();
bootstrapWithPortForwarding(peerDHT, futureDiscover); bootstrapWithPortForwarding(peerDHT, futureDiscover);
break; break;
case "default": case "default":
@ -227,8 +229,8 @@ public class BootstrappedPeerFactory {
public void operationComplete(BaseFuture future) throws Exception { public void operationComplete(BaseFuture future) throws Exception {
if (future.isSuccess()) { if (future.isSuccess()) {
// Port forwarding has succeed // Port forwarding has succeed
log.debug("Port forwarding was successful. My address visible to the outside is " + futureNAT log.debug("Port forwarding was successful. My address visible to the outside is " +
.peerAddress()); futureNAT.peerAddress());
requestBootstrapPeerMap(); requestBootstrapPeerMap();
settableFuture.set(peerDHT); settableFuture.set(peerDHT);

View file

@ -172,8 +172,8 @@ public class MessageFacade implements MessageBroker {
if (future.isSuccess()) { if (future.isSuccess()) {
Platform.runLater(() -> { Platform.runLater(() -> {
addOfferListener.onComplete(); addOfferListener.onComplete();
orderBookListeners.stream().forEach(listener -> listener.onOfferAdded(data, orderBookListeners.stream().forEach(listener ->
future.isSuccess())); listener.onOfferAdded(data, future.isSuccess()));
// TODO will be removed when we don't use polling anymore // TODO will be removed when we don't use polling anymore
setDirty(locationKey); setDirty(locationKey);
@ -214,8 +214,8 @@ public class MessageFacade implements MessageBroker {
@Override @Override
public void operationComplete(BaseFuture future) throws Exception { public void operationComplete(BaseFuture future) throws Exception {
Platform.runLater(() -> { Platform.runLater(() -> {
orderBookListeners.stream().forEach(orderBookListener -> orderBookListener.onOfferRemoved orderBookListeners.stream().forEach(orderBookListener ->
(data, future.isSuccess())); orderBookListener.onOfferRemoved(data, future.isSuccess()));
setDirty(locationKey); setDirty(locationKey);
}); });
if (future.isSuccess()) { if (future.isSuccess()) {
@ -293,8 +293,8 @@ public class MessageFacade implements MessageBroker {
addFuture.addListener(new BaseFutureAdapter<BaseFuture>() { addFuture.addListener(new BaseFutureAdapter<BaseFuture>() {
@Override @Override
public void operationComplete(BaseFuture future) throws Exception { public void operationComplete(BaseFuture future) throws Exception {
Platform.runLater(() -> arbitratorListeners.stream().forEach(listener -> listener Platform.runLater(() -> arbitratorListeners.stream().forEach(listener ->
.onArbitratorAdded(arbitratorData, addFuture.isSuccess()))); listener.onArbitratorAdded(arbitratorData, addFuture.isSuccess())));
if (addFuture.isSuccess()) { if (addFuture.isSuccess()) {
log.trace("Add arbitrator to DHT was successful. Stored data: [key: " + locationKey + ", " + log.trace("Add arbitrator to DHT was successful. Stored data: [key: " + locationKey + ", " +
"values: " + arbitratorData + "]"); "values: " + arbitratorData + "]");
@ -317,8 +317,8 @@ public class MessageFacade implements MessageBroker {
removeFuture.addListener(new BaseFutureAdapter<BaseFuture>() { removeFuture.addListener(new BaseFutureAdapter<BaseFuture>() {
@Override @Override
public void operationComplete(BaseFuture future) throws Exception { public void operationComplete(BaseFuture future) throws Exception {
Platform.runLater(() -> arbitratorListeners.stream().forEach(listener -> listener.onArbitratorRemoved Platform.runLater(() -> arbitratorListeners.stream().forEach(listener ->
(arbitratorData, removeFuture.isSuccess()))); listener.onArbitratorRemoved(arbitratorData, removeFuture.isSuccess())));
if (removeFuture.isSuccess()) { if (removeFuture.isSuccess()) {
log.trace("Remove arbitrator from DHT was successful. Stored data: [key: " + locationKey + ", " + log.trace("Remove arbitrator from DHT was successful. Stored data: [key: " + locationKey + ", " +
"values: " + arbitratorData + "]"); "values: " + arbitratorData + "]");
@ -472,8 +472,8 @@ public class MessageFacade implements MessageBroker {
public void handleMessage(Object message, PeerAddress peerAddress) { public void handleMessage(Object message, PeerAddress peerAddress) {
if (message instanceof TradeMessage) { if (message instanceof TradeMessage) {
log.error("####################"); log.error("####################");
Platform.runLater(() -> incomingTradeMessageListeners.stream().forEach(e -> e.onMessage((TradeMessage) Platform.runLater(() -> incomingTradeMessageListeners.stream().forEach(e ->
message, peerAddress))); e.onMessage((TradeMessage) message, peerAddress)));
} }
} }
} }

View file

@ -161,8 +161,8 @@ public class P2PNode {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// The data and the domain are protected by that key pair. // The data and the domain are protected by that key pair.
public FuturePut putDomainProtectedData(Number160 locationKey, Data data) throws IOException, public FuturePut putDomainProtectedData(Number160 locationKey, Data data)
ClassNotFoundException { throws IOException, ClassNotFoundException {
data.protectEntry(keyPair); data.protectEntry(keyPair);
final Number160 ownerKeyHash = Utils.makeSHAHash(keyPair.getPublic().getEncoded()); final Number160 ownerKeyHash = Utils.makeSHAHash(keyPair.getPublic().getEncoded());
return peerDHT.put(locationKey).data(data).keyPair(keyPair).domainKey(ownerKeyHash).protectDomain().start(); return peerDHT.put(locationKey).data(data).keyPair(keyPair).domainKey(ownerKeyHash).protectDomain().start();
@ -174,8 +174,8 @@ public class P2PNode {
} }
// Not public readable. Only users with the public key of the peer who stored the data can read that data // Not public readable. Only users with the public key of the peer who stored the data can read that data
public FutureGet getDomainProtectedData(Number160 locationKey, PublicKey publicKey) throws IOException, public FutureGet getDomainProtectedData(Number160 locationKey, PublicKey publicKey)
ClassNotFoundException { throws IOException, ClassNotFoundException {
final Number160 ownerKeyHash = Utils.makeSHAHash(publicKey.getEncoded()); final Number160 ownerKeyHash = Utils.makeSHAHash(publicKey.getEncoded());
return peerDHT.get(locationKey).domainKey(ownerKeyHash).start(); return peerDHT.get(locationKey).domainKey(ownerKeyHash).start();
} }

View file

@ -214,8 +214,8 @@ public class TradeManager {
Trade trade = createTrade(offer); Trade trade = createTrade(offer);
trade.setTradeAmount(amount); trade.setTradeAmount(amount);
ProtocolForTakerAsSeller protocolForTakerAsSeller = new ProtocolForTakerAsSeller(trade, listener, ProtocolForTakerAsSeller protocolForTakerAsSeller = new ProtocolForTakerAsSeller(
messageFacade, walletFacade, blockChainFacade, cryptoFacade, user); trade, listener, messageFacade, walletFacade, blockChainFacade, cryptoFacade, user);
takerAsSellerProtocolMap.put(trade.getId(), protocolForTakerAsSeller); takerAsSellerProtocolMap.put(trade.getId(), protocolForTakerAsSeller);
protocolForTakerAsSeller.start(); protocolForTakerAsSeller.start();

View file

@ -118,8 +118,8 @@ public class OrderBook implements OrderBookListener {
boolean countryResult = countryInList(offer.getBankAccountCountry(), settings.getAcceptedCountries()); boolean countryResult = countryInList(offer.getBankAccountCountry(), settings.getAcceptedCountries());
// One of the supported languages from the settings must match one of the offer languages (n to n) // One of the supported languages from the settings must match one of the offer languages (n to n)
boolean languageResult = languagesInList(settings.getAcceptedLanguageLocales(), boolean languageResult =
offer.getAcceptedLanguageLocales()); languagesInList(settings.getAcceptedLanguageLocales(), offer.getAcceptedLanguageLocales());
// Apply applyFilter only if there is a valid value set // Apply applyFilter only if there is a valid value set
// The requested amount must be lower or equal then the offer amount // The requested amount must be lower or equal then the offer amount

View file

@ -44,8 +44,8 @@ public class BroadCastOfferFeeTx {
faultHandler.onFault("Offer fee payment failed.", e); faultHandler.onFault("Offer fee payment failed.", e);
} }
} else { } else {
faultHandler.onFault("Offer fee payment failed.", new Exception("Offer fee payment failed. " + faultHandler.onFault("Offer fee payment failed.",
"Transaction = null.")); new Exception("Offer fee payment failed. Transaction = null."));
} }
} }
@ -55,10 +55,10 @@ public class BroadCastOfferFeeTx {
} }
}); });
} catch (InsufficientMoneyException e) { } catch (InsufficientMoneyException e) {
faultHandler.onFault("Offer fee payment failed because there is insufficient money in the trade pocket. " + faultHandler.onFault(
"", e); "Offer fee payment failed because there is insufficient money in the trade pocket.", e);
} catch (Throwable t) { } catch (Throwable t) {
faultHandler.onFault("Offer fee payment failed because of an exception occurred. ", t); faultHandler.onFault("Offer fee payment failed because an exception occurred.", t);
} }
} }
} }

View file

@ -39,8 +39,8 @@ public class CreateDepositTx {
log.trace("Run task"); log.trace("Run task");
try { try {
String offererPubKey = walletFacade.getAddressInfoByTradeID(tradeId).getPubKeyAsHexString(); String offererPubKey = walletFacade.getAddressInfoByTradeID(tradeId).getPubKeyAsHexString();
Transaction transaction = walletFacade.offererCreatesMSTxAndAddPayment(offererInputAmount, offererPubKey, Transaction transaction = walletFacade.offererCreatesMSTxAndAddPayment(
takerMultiSigPubKey, arbitratorPubKeyAsHex, tradeId); offererInputAmount, offererPubKey, takerMultiSigPubKey, arbitratorPubKeyAsHex, tradeId);
String preparedOffererDepositTxAsHex = Utils.HEX.encode(transaction.bitcoinSerialize()); String preparedOffererDepositTxAsHex = Utils.HEX.encode(transaction.bitcoinSerialize());
long offererTxOutIndex = transaction.getInput(0).getOutpoint().getIndex(); long offererTxOutIndex = transaction.getInput(0).getOutpoint().getIndex();
@ -48,8 +48,8 @@ public class CreateDepositTx {
resultHandler.onResult(offererPubKey, preparedOffererDepositTxAsHex, offererTxOutIndex); resultHandler.onResult(offererPubKey, preparedOffererDepositTxAsHex, offererTxOutIndex);
} catch (InsufficientMoneyException e) { } catch (InsufficientMoneyException e) {
log.error("Create deposit tx faultHandler.onFault due InsufficientMoneyException " + e); log.error("Create deposit tx faultHandler.onFault due InsufficientMoneyException " + e);
exceptionHandler.onError(new Exception("Create deposit tx faultHandler.onFault due " + exceptionHandler.onError(
"InsufficientMoneyException " + e)); new Exception("Create deposit tx faultHandler.onFault due InsufficientMoneyException " + e));
} }
} }

View file

@ -35,8 +35,9 @@ public class HandleTakeOfferRequest {
if (!takeOfferRequestAccepted) { if (!takeOfferRequestAccepted) {
log.info("Received take offer request but the offer not marked as open anymore."); log.info("Received take offer request but the offer not marked as open anymore.");
} }
messageFacade.sendTradeMessage(peerAddress, new RespondToTakeOfferRequestMessage(tradeId, RespondToTakeOfferRequestMessage tradeMessage =
takeOfferRequestAccepted), new OutgoingTradeMessageListener() { new RespondToTakeOfferRequestMessage(tradeId, takeOfferRequestAccepted);
messageFacade.sendTradeMessage(peerAddress, tradeMessage, new OutgoingTradeMessageListener() {
@Override @Override
public void onResult() { public void onResult() {
log.trace("RespondToTakeOfferRequestMessage successfully arrived at peer"); log.trace("RespondToTakeOfferRequestMessage successfully arrived at peer");

View file

@ -354,8 +354,8 @@ public class ProtocolForOffererAsBuyer {
log.debug("state " + state); log.debug("state " + state);
// validation // validation
checkState(state.ordinal() >= State.SignAndPublishDepositTx.ordinal() && state.ordinal() <= State checkState(state.ordinal() >= State.SignAndPublishDepositTx.ordinal() &&
.onResultSetupListenerForBlockChainConfirmation.ordinal()); state.ordinal() <= State.onResultSetupListenerForBlockChainConfirmation.ordinal());
state = State.onUIEventBankTransferInited; state = State.onUIEventBankTransferInited;
@ -423,5 +423,4 @@ public class ProtocolForOffererAsBuyer {
listener.onFault(throwable, state); listener.onFault(throwable, state);
} }
} }

View file

@ -40,8 +40,8 @@ public class RequestTakerDepositPayment {
String preparedOffererDepositTxAsHex, String preparedOffererDepositTxAsHex,
long offererTxOutIndex) { long offererTxOutIndex) {
log.trace("Run task"); log.trace("Run task");
RequestTakerDepositPaymentMessage tradeMessage = new RequestTakerDepositPaymentMessage(tradeId, bankAccount, RequestTakerDepositPaymentMessage tradeMessage = new RequestTakerDepositPaymentMessage(
accountId, offererPubKey, preparedOffererDepositTxAsHex, offererTxOutIndex); tradeId, bankAccount, accountId, offererPubKey, preparedOffererDepositTxAsHex, offererTxOutIndex);
messageFacade.sendTradeMessage(peerAddress, tradeMessage, new OutgoingTradeMessageListener() { messageFacade.sendTradeMessage(peerAddress, tradeMessage, new OutgoingTradeMessageListener() {
@Override @Override
public void onResult() { public void onResult() {

View file

@ -33,8 +33,9 @@ public class SendDepositTxIdToTaker {
public static void run(ResultHandler resultHandler, ExceptionHandler exceptionHandler, PeerAddress peerAddress, public static void run(ResultHandler resultHandler, ExceptionHandler exceptionHandler, PeerAddress peerAddress,
MessageFacade messageFacade, String tradeId, Transaction depositTransaction) { MessageFacade messageFacade, String tradeId, Transaction depositTransaction) {
log.trace("Run task"); log.trace("Run task");
DepositTxPublishedMessage tradeMessage = new DepositTxPublishedMessage(tradeId, DepositTxPublishedMessage tradeMessage =
Utils.HEX.encode(depositTransaction.bitcoinSerialize())); new DepositTxPublishedMessage(tradeId, Utils.HEX.encode(depositTransaction.bitcoinSerialize()));
messageFacade.sendTradeMessage(peerAddress, tradeMessage, new OutgoingTradeMessageListener() { messageFacade.sendTradeMessage(peerAddress, tradeMessage, new OutgoingTradeMessageListener() {
@Override @Override
public void onResult() { public void onResult() {

View file

@ -48,8 +48,8 @@ public class SendSignedPayoutTx {
Coin offererPaybackAmount = tradeAmount.add(collateral); Coin offererPaybackAmount = tradeAmount.add(collateral);
Coin takerPaybackAmount = collateral; Coin takerPaybackAmount = collateral;
Pair<ECKey.ECDSASignature, String> result = walletFacade.offererCreatesAndSignsPayoutTx Pair<ECKey.ECDSASignature, String> result = walletFacade.offererCreatesAndSignsPayoutTx(
(depositTransactionId, offererPaybackAmount, takerPaybackAmount, takerPayoutAddress, tradeId); depositTransactionId, offererPaybackAmount, takerPaybackAmount, takerPayoutAddress, tradeId);
ECKey.ECDSASignature offererSignature = result.getKey(); ECKey.ECDSASignature offererSignature = result.getKey();
String offererSignatureR = offererSignature.r.toString(); String offererSignatureR = offererSignature.r.toString();

View file

@ -40,8 +40,8 @@ public class SetupListenerForBlockChainConfirmation {
if (reason == ChangeReason.SEEN_PEERS) { if (reason == ChangeReason.SEEN_PEERS) {
listener.onDepositTxConfirmedUpdate(tx.getConfidence()); listener.onDepositTxConfirmedUpdate(tx.getConfidence());
} }
if (reason == ChangeReason.TYPE && tx.getConfidence().getConfidenceType() == TransactionConfidence if (reason == ChangeReason.TYPE &&
.ConfidenceType.BUILDING) { tx.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) {
listener.onDepositTxConfirmedInBlockchain(); listener.onDepositTxConfirmedInBlockchain();
depositTransaction.getConfidence().removeEventListener(this); depositTransaction.getConfidence().removeEventListener(this);
log.trace("Tx is in blockchain"); log.trace("Tx is in blockchain");

View file

@ -55,8 +55,8 @@ public class PayDeposit {
resultHandler.onResult(signedTakerDepositTx); resultHandler.onResult(signedTakerDepositTx);
} catch (InsufficientMoneyException e) { } catch (InsufficientMoneyException e) {
log.error("Pay deposit faultHandler.onFault due InsufficientMoneyException " + e); log.error("Pay deposit faultHandler.onFault due InsufficientMoneyException " + e);
exceptionHandler.onError(new Exception("Pay deposit faultHandler.onFault due InsufficientMoneyException " exceptionHandler.onError(
+ e)); new Exception("Pay deposit faultHandler.onFault due InsufficientMoneyException " + e));
} }
} }

View file

@ -42,14 +42,14 @@ public class PayTakeOfferFee {
@Override @Override
public void onFailure(Throwable t) { public void onFailure(Throwable t) {
log.error("Take offer fee paid faultHandler.onFault with exception: " + t); log.error("Take offer fee paid faultHandler.onFault with exception: " + t);
exceptionHandler.onError(new Exception("Take offer fee paid faultHandler.onFault with exception: " + exceptionHandler.onError(
"" + t)); new Exception("Take offer fee paid faultHandler.onFault with exception: " + t));
} }
}); });
} catch (InsufficientMoneyException e) { } catch (InsufficientMoneyException e) {
log.error("Take offer fee paid faultHandler.onFault due InsufficientMoneyException " + e); log.error("Take offer fee paid faultHandler.onFault due InsufficientMoneyException " + e);
exceptionHandler.onError(new Exception("Take offer fee paid faultHandler.onFault due " + exceptionHandler.onError(
"InsufficientMoneyException " + e)); new Exception("Take offer fee paid faultHandler.onFault due to InsufficientMoneyException " + e));
} }
} }

View file

@ -318,8 +318,8 @@ public class ProtocolForTakerAsSeller {
log.debug("onBankTransferInitedMessage called " + step++); log.debug("onBankTransferInitedMessage called " + step++);
log.debug("state " + state); log.debug("state " + state);
// validate // validate
checkState(state.ordinal() >= State.SendSignedTakerDepositTxAsHex.ordinal() && state.ordinal() < State checkState(state.ordinal() >= State.SendSignedTakerDepositTxAsHex.ordinal() &&
.SignAndPublishPayoutTx.ordinal()); state.ordinal() < State.SignAndPublishPayoutTx.ordinal());
checkArgument(tradeId.equals(message.getTradeId())); checkArgument(tradeId.equals(message.getTradeId()));
String depositTxAsHex = nonEmptyStringOf(message.getDepositTxAsHex()); String depositTxAsHex = nonEmptyStringOf(message.getDepositTxAsHex());
String offererSignatureR = nonEmptyStringOf(message.getOffererSignatureR()); String offererSignatureR = nonEmptyStringOf(message.getOffererSignatureR());

View file

@ -33,17 +33,17 @@ public class RequestTakeOffer {
log.trace("Run task"); log.trace("Run task");
messageFacade.sendTradeMessage(peerAddress, new RequestTakeOfferMessage(tradeId), messageFacade.sendTradeMessage(peerAddress, new RequestTakeOfferMessage(tradeId),
new OutgoingTradeMessageListener() { new OutgoingTradeMessageListener() {
@Override @Override
public void onResult() { public void onResult() {
log.trace("RequestTakeOfferMessage successfully arrived at peer"); log.trace("RequestTakeOfferMessage successfully arrived at peer");
resultHandler.onResult(); resultHandler.onResult();
} }
@Override @Override
public void onFailed() { public void onFailed() {
log.error("RequestTakeOfferMessage did not arrive at peer"); log.error("RequestTakeOfferMessage did not arrive at peer");
exceptionHandler.onError(new Exception("RequestTakeOfferMessage did not arrive at peer")); exceptionHandler.onError(new Exception("RequestTakeOfferMessage did not arrive at peer"));
} }
}); });
} }
} }

View file

@ -76,8 +76,8 @@ public class SendSignedTakerDepositTxAsHex {
@Override @Override
public void onFailed() { public void onFailed() {
log.error("RequestOffererDepositPublicationMessage did not arrive at peer"); log.error("RequestOffererDepositPublicationMessage did not arrive at peer");
exceptionHandler.onError(new Exception("RequestOffererDepositPublicationMessage did not arrive at " + exceptionHandler.onError(
"peer")); new Exception("RequestOffererDepositPublicationMessage did not arrive at peer"));
} }
}); });
} }

View file

@ -52,22 +52,21 @@ public class StorageDirectory {
} }
public static File getApplicationDirectory() { public static File getApplicationDirectory() {
File executionRoot = new File(StorageDirectory.class.getProtectionDomain().getCodeSource().getLocation() File executionRoot =
.getFile()); new File(StorageDirectory.class.getProtectionDomain().getCodeSource().getLocation().getFile());
try { try {
log.trace("executionRoot " + executionRoot.getCanonicalPath()); log.trace("executionRoot " + executionRoot.getCanonicalPath());
// check if it is packed into a mac app (e.g.: "/Users/mk/Desktop/bitsquare.app/Contents/Java/bitsquare // check if it is packed into a mac app (e.g.: "$HOME/Desktop/bitsquare.app/Contents/Java/bitsquare.jar")
// .jar") if (executionRoot.getCanonicalPath().endsWith(".app/Contents/Java/bitsquare.jar") &&
if (executionRoot.getCanonicalPath().endsWith(".app/Contents/Java/bitsquare.jar") && System.getProperty System.getProperty("os.name").startsWith("Mac"))
("os.name").startsWith("Mac"))
return executionRoot.getParentFile().getParentFile().getParentFile().getParentFile(); return executionRoot.getParentFile().getParentFile().getParentFile().getParentFile();
else if (executionRoot.getCanonicalPath().endsWith(File.separator + "target" + File.separator + "classes")) else if (executionRoot.getCanonicalPath().endsWith(File.separator + "target" + File.separator + "classes"))
return executionRoot.getParentFile(); // dev e.g.: return executionRoot.getParentFile(); // dev e.g.:
// /Users/mk/Documents/_intellij/bitsquare/target/classes -> use target as root // $HOME/Documents/_intellij/bitsquare/target/classes -> use target as root
else if (executionRoot.getCanonicalPath().endsWith(File.separator + "bitsquare.jar")) else if (executionRoot.getCanonicalPath().endsWith(File.separator + "bitsquare.jar"))
return executionRoot.getParentFile(); // dev with jar e.g.: return executionRoot.getParentFile(); // dev with jar e.g.:
// Users/mk/Documents/_intellij/bitsquare/out/artifacts/bitsquare2/bitsquare.jar -> use target as root // $HOME/Documents/_intellij/bitsquare/out/artifacts/bitsquare2/bitsquare.jar -> use target as root
else else
return executionRoot; return executionRoot;
} catch (IOException e) { } catch (IOException e) {
@ -91,8 +90,8 @@ public class StorageDirectory {
if (!storageDirectory.exists()) { if (!storageDirectory.exists()) {
boolean created = storageDirectory.mkdir(); boolean created = storageDirectory.mkdir();
if (!created) if (!created)
throw new RuntimeException("Could not create the application data directory of '" + storageDirectory throw new RuntimeException(
+ "'"); "Could not create the application data directory of '" + storageDirectory + "'");
} }
} }
} }

View file

@ -35,14 +35,14 @@ public class Utilities {
private static long lastTimeStamp = System.currentTimeMillis(); private static long lastTimeStamp = System.currentTimeMillis();
public static String objectToJson(Object object) { public static String objectToJson(Object object) {
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting() Gson gson =
.create(); new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create();
return gson.toJson(object); return gson.toJson(object);
} }
public static <T> T jsonToObject(String jsonString, Class<T> classOfT) { public static <T> T jsonToObject(String jsonString, Class<T> classOfT) {
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting() Gson gson =
.create(); new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create();
return gson.fromJson(jsonString, classOfT); return gson.fromJson(jsonString, classOfT);
} }

View file

@ -146,8 +146,8 @@ public class P2PNodeTest {
data.protectEntry(keyPairOtherPeer); data.protectEntry(keyPairOtherPeer);
// he use the pub key from the client // he use the pub key from the client
final Number160 keyHash = Utils.makeSHAHash(keyPairClient.getPublic().getEncoded()); final Number160 keyHash = Utils.makeSHAHash(keyPairClient.getPublic().getEncoded());
futurePut = otherPeer.put(locationKey).data(data).keyPair(keyPairOtherPeer).domainKey(keyHash).protectDomain futurePut = otherPeer.put(locationKey).data(data).keyPair(keyPairOtherPeer).domainKey(keyHash)
().start(); .protectDomain().start();
futurePut.awaitUninterruptibly(); futurePut.awaitUninterruptibly();
assertFalse(futurePut.isSuccess()); assertFalse(futurePut.isSuccess());
@ -169,8 +169,7 @@ public class P2PNodeTest {
} }
@Test @Test
public void testChangeEntryProtectionKey() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, public void testChangeEntryProtectionKey() throws Exception {
InterruptedException, InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair1 = gen.generateKeyPair();
@ -191,8 +190,8 @@ public class P2PNodeTest {
Data data2 = new Data().protectEntry(keyPair2); Data data2 = new Data().protectEntry(keyPair2);
data2.publicKey(keyPair2.getPublic()); data2.publicKey(keyPair2.getPublic());
FuturePut fp3 = p1.put(Number160.createHash("key1")).sign().putMeta().data(data2).start() FuturePut fp3 =
.awaitUninterruptibly(); p1.put(Number160.createHash("key1")).sign().putMeta().data(data2).start().awaitUninterruptibly();
Assert.assertTrue(fp3.isSuccess()); Assert.assertTrue(fp3.isSuccess());
FuturePut fp4 = p2.put(Number160.createHash("key1")).sign().data(data).start().awaitUninterruptibly(); FuturePut fp4 = p2.put(Number160.createHash("key1")).sign().data(data).start().awaitUninterruptibly();

View file

@ -1,20 +1,3 @@
/*
* This file is part of Bitsquare.
*
* Bitsquare is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bitsquare is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
/* /*
* Copyright 2012 Thomas Bocek * Copyright 2012 Thomas Bocek
* *
@ -90,9 +73,8 @@ public class UtilsDHT2 {
return createAddress(new Number160(id), "127.0.0.1", 8005, 8006, false, false); return createAddress(new Number160(id), "127.0.0.1", 8005, 8006, false, false);
} }
public static PeerAddress createAddress(Number160 idSender, String inetSender, int tcpPortSender, public static PeerAddress createAddress(Number160 idSender, String inetSender, int tcpPortSender, int udpPortSender,
int udpPortSender, boolean firewallUDP, boolean firewallUDP, boolean firewallTCP) throws UnknownHostException {
boolean firewallTCP) throws UnknownHostException {
InetAddress inetSend = InetAddress.getByName(inetSender); InetAddress inetSend = InetAddress.getByName(inetSender);
PeerSocketAddress peerSocketAddress = new PeerSocketAddress(inetSend, tcpPortSender, udpPortSender); PeerSocketAddress peerSocketAddress = new PeerSocketAddress(inetSend, tcpPortSender, udpPortSender);
PeerAddress n1 = new PeerAddress(idSender, peerSocketAddress, firewallTCP, firewallUDP, false, PeerAddress n1 = new PeerAddress(idSender, peerSocketAddress, firewallTCP, firewallUDP, false,
@ -102,10 +84,8 @@ public class UtilsDHT2 {
public static Message createDummyMessage(Number160 idSender, String inetSender, int tcpPortSendor, public static Message createDummyMessage(Number160 idSender, String inetSender, int tcpPortSendor,
int udpPortSender, Number160 idRecipien, String inetRecipient, int udpPortSender, Number160 idRecipien, String inetRecipient,
int tcpPortRecipient, int tcpPortRecipient, int udpPortRecipient, byte command, Type type,
int udpPortRecipient, byte command, Type type, boolean firewallUDP, boolean firewallUDP, boolean firewallTCP) throws UnknownHostException {
boolean firewallTCP)
throws UnknownHostException {
Message message = new Message(); Message message = new Message();
PeerAddress n1 = createAddress(idSender, inetSender, tcpPortSendor, udpPortSender, firewallUDP, PeerAddress n1 = createAddress(idSender, inetSender, tcpPortSendor, udpPortSender, firewallUDP,
firewallTCP); firewallTCP);