Rename methods, cleanup

This commit is contained in:
Manfred Karrer 2015-03-12 11:12:54 +01:00
parent 9c9064091a
commit 6888eacc24
13 changed files with 233 additions and 262 deletions

View file

@ -162,11 +162,6 @@ public class MainView extends InitializableView<StackPane, MainViewModel> {
} }
}); });
model.featureNotImplementedWarning.addListener((ov, oldValue, newValue) -> {
if (oldValue == null && newValue != null)
Popups.openWarningPopup(newValue);
});
// Delay a bit to give time for rendering the splash screen // Delay a bit to give time for rendering the splash screen
Platform.runLater(() -> model.initBackend()); Platform.runLater(() -> model.initBackend());
} }

View file

@ -96,7 +96,6 @@ class MainViewModel implements ViewModel {
final ObjectProperty<BankAccount> currentBankAccount = new SimpleObjectProperty<>(); final ObjectProperty<BankAccount> currentBankAccount = new SimpleObjectProperty<>();
final BooleanProperty showAppScreen = new SimpleBooleanProperty(); final BooleanProperty showAppScreen = new SimpleBooleanProperty();
final StringProperty featureNotImplementedWarning = new SimpleStringProperty();
final StringProperty numPendingTradesAsString = new SimpleStringProperty(); final StringProperty numPendingTradesAsString = new SimpleStringProperty();
final BooleanProperty showPendingTradesNotification = new SimpleBooleanProperty(); final BooleanProperty showPendingTradesNotification = new SimpleBooleanProperty();
@ -142,13 +141,6 @@ class MainViewModel implements ViewModel {
}); });
bankAccountsComboBoxDisable.set(user.getBankAccounts().isEmpty()); bankAccountsComboBoxDisable.set(user.getBankAccounts().isEmpty());
bankAccountsComboBoxPrompt.set(user.getBankAccounts().isEmpty() ? "No accounts" : ""); bankAccountsComboBoxPrompt.set(user.getBankAccounts().isEmpty() ? "No accounts" : "");
tradeManager.featureNotImplementedWarningProperty().addListener((ov, oldValue, newValue) -> {
if (oldValue == null && newValue != null) {
featureNotImplementedWarning.set(newValue);
tradeManager.setFeatureNotImplementedWarning(null);
}
});
} }
public void restart() { public void restart() {

View file

@ -79,7 +79,7 @@ class OffersDataModel implements Activatable, DataModel {
} }
void removeOpenOffer(String offerId, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) { void removeOpenOffer(String offerId, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
tradeManager.requestRemoveOpenOffer(offerId, resultHandler, errorMessageHandler); tradeManager.onRemoveOpenOfferRequested(offerId, resultHandler, errorMessageHandler);
} }

View file

@ -164,12 +164,12 @@ class PendingTradesDataModel implements Activatable, DataModel {
void fiatPaymentStarted() { void fiatPaymentStarted() {
getTrade().setState(Trade.State.FIAT_PAYMENT_STARTED); getTrade().setState(Trade.State.FIAT_PAYMENT_STARTED);
tradeManager.fiatPaymentStarted(getTrade().getId()); tradeManager.onFiatPaymentStarted(getTrade().getId());
} }
void fiatPaymentReceived() { void fiatPaymentReceived() {
getTrade().setState(Trade.State.FIAT_PAYMENT_RECEIVED); getTrade().setState(Trade.State.FIAT_PAYMENT_RECEIVED);
tradeManager.fiatPaymentReceived(getTrade().getId()); tradeManager.onFiatPaymentReceived(getTrade().getId());
} }
void withdraw(String toAddress) { void withdraw(String toAddress) {
@ -200,7 +200,7 @@ class PendingTradesDataModel implements Activatable, DataModel {
log.error(e.getMessage()); log.error(e.getMessage());
} }
tradeManager.closeTrade(getTrade()); tradeManager.onCloseTradeRequested(getTrade());
/* /*
Action response = Popups.openConfirmPopup( Action response = Popups.openConfirmPopup(

View file

@ -172,7 +172,7 @@ class CreateOfferDataModel implements Activatable, DataModel {
void placeOffer() { void placeOffer() {
// data validation is done in the trade domain // data validation is done in the trade domain
tradeManager.requestPlaceOffer(offerId, tradeManager.onPlaceOfferRequested(offerId,
direction, direction,
priceAsFiat.get(), priceAsFiat.get(),
amountAsCoin.get(), amountAsCoin.get(),

View file

@ -115,7 +115,7 @@ class OfferBookDataModel implements Activatable, DataModel {
} }
void removeOpenOffer(String offerId, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) { void removeOpenOffer(String offerId, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
tradeManager.requestRemoveOpenOffer(offerId, resultHandler, errorMessageHandler); tradeManager.onRemoveOpenOfferRequested(offerId, resultHandler, errorMessageHandler);
} }
void calculateVolume() { void calculateVolume() {

View file

@ -103,7 +103,7 @@ class TakeOfferDataModel implements Activatable, DataModel {
@Override @Override
public void deactivate() { public void deactivate() {
btcCode.unbind(); btcCode.unbind();
tradeManager.stopRequestIsOfferAvailableRequest(offer); tradeManager.onGetOfferAvailableStateRequestCanceled(offer);
} }
void initWithData(Coin amount, Offer offer) { void initWithData(Coin amount, Offer offer) {
@ -134,11 +134,11 @@ class TakeOfferDataModel implements Activatable, DataModel {
offer.getStateProperty().addListener((observable, oldValue, newValue) -> { offer.getStateProperty().addListener((observable, oldValue, newValue) -> {
offerIsAvailable.set(newValue); offerIsAvailable.set(newValue);
}); });
tradeManager.requestIsOfferAvailable(offer); tradeManager.onGetOfferAvailableStateRequested(offer);
} }
void takeOffer() { void takeOffer() {
final Trade trade = tradeManager.requestTakeOffer(amountAsCoin.get(), offer); final Trade trade = tradeManager.onTakeOfferRequested(amountAsCoin.get(), offer);
trade.stateProperty().addListener((ov, oldValue, newValue) -> { trade.stateProperty().addListener((ov, oldValue, newValue) -> {
log.debug("trade state = " + newValue); log.debug("trade state = " + newValue);
switch (newValue) { switch (newValue) {

View file

@ -54,7 +54,7 @@ public class OfferBook {
private final User user; private final User user;
private final ObservableList<OfferBookListItem> offerBookListItems = FXCollections.observableArrayList(); private final ObservableList<OfferBookListItem> offerBookListItems = FXCollections.observableArrayList();
private final OfferBookService.Listener remoteOfferBookListener; private final OfferBookService.Listener offerBookServiceListener;
private final ChangeListener<BankAccount> bankAccountChangeListener; private final ChangeListener<BankAccount> bankAccountChangeListener;
private final ChangeListener<Number> invalidationListener; private final ChangeListener<Number> invalidationListener;
private String fiatCode; private String fiatCode;
@ -75,7 +75,7 @@ public class OfferBook {
bankAccountChangeListener = (observableValue, oldValue, newValue) -> setBankAccount(newValue); bankAccountChangeListener = (observableValue, oldValue, newValue) -> setBankAccount(newValue);
invalidationListener = (ov, oldValue, newValue) -> requestGetOffers(); invalidationListener = (ov, oldValue, newValue) -> requestGetOffers();
remoteOfferBookListener = new OfferBookService.Listener() { offerBookServiceListener = new OfferBookService.Listener() {
@Override @Override
public void onOfferAdded(Offer offer) { public void onOfferAdded(Offer offer) {
addOfferToOfferBookListItems(offer); addOfferToOfferBookListItems(offer);
@ -150,14 +150,14 @@ public class OfferBook {
private void addListeners() { private void addListeners() {
log.debug("addListeners "); log.debug("addListeners ");
user.currentBankAccountProperty().addListener(bankAccountChangeListener); user.currentBankAccountProperty().addListener(bankAccountChangeListener);
offerBookService.addListener(remoteOfferBookListener); offerBookService.addListener(offerBookServiceListener);
offerBookService.invalidationTimestampProperty().addListener(invalidationListener); offerBookService.invalidationTimestampProperty().addListener(invalidationListener);
} }
private void removeListeners() { private void removeListeners() {
log.debug("removeListeners "); log.debug("removeListeners ");
user.currentBankAccountProperty().removeListener(bankAccountChangeListener); user.currentBankAccountProperty().removeListener(bankAccountChangeListener);
offerBookService.removeListener(remoteOfferBookListener); offerBookService.removeListener(offerBookServiceListener);
offerBookService.invalidationTimestampProperty().removeListener(invalidationListener); offerBookService.invalidationTimestampProperty().removeListener(invalidationListener);
} }

View file

@ -52,8 +52,6 @@ import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ObservableMap; import javafx.collections.ObservableMap;
@ -91,7 +89,6 @@ public class TradeManager {
// the latest pending trade // the latest pending trade
private Trade currentPendingTrade; private Trade currentPendingTrade;
final StringProperty featureNotImplementedWarning = new SimpleStringProperty();
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -141,10 +138,26 @@ public class TradeManager {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Manage offers // Called from UI
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void requestPlaceOffer(String id, public void onGetOfferAvailableStateRequested(Offer offer) {
if (!requestIsOfferAvailableProtocolMap.containsKey(offer.getId())) {
RequestIsOfferAvailableProtocol protocol = new RequestIsOfferAvailableProtocol(offer, tradeMessageService);
requestIsOfferAvailableProtocolMap.put(offer.getId(), protocol);
protocol.start();
}
else {
log.warn("requestIsOfferAvailable already called for offer with ID:" + offer.getId());
}
}
// When closing take offer view, we are not interested in the requestIsOfferAvailable result anymore, so remove from the map
public void onGetOfferAvailableStateRequestCanceled(Offer offer) {
requestIsOfferAvailableProtocolMap.remove(offer.getId());
}
public void onPlaceOfferRequested(String id,
Direction direction, Direction direction,
Fiat price, Fiat price,
Coin amount, Coin amount,
@ -174,147 +187,22 @@ public class TradeManager {
walletService, walletService,
offerBookService, offerBookService,
(transaction) -> { (transaction) -> {
createOpenOffer(offer); OpenOffer openOffer = createOpenOffer(offer);
createOffererAsBuyerProtocol(openOffer);
resultHandler.handleResult(transaction); resultHandler.handleResult(transaction);
}, },
(message, throwable) -> errorMessageHandler.handleErrorMessage(message) (message, throwable) -> errorMessageHandler.handleErrorMessage(message)
); );
placeOfferProtocol.placeOffer(); placeOfferProtocol.onPlaceOfferRequested();
} }
private void createOpenOffer(Offer offer) { public void onRemoveOpenOfferRequested(String offerId, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
OpenOffer openOffer = new OpenOffer(offer); removeOpenOffer(offerId, resultHandler, errorMessageHandler, true);
openOffers.put(openOffer.getId(), openOffer);
persistOpenOffers();
createOffererAsBuyerProtocol(openOffer);
}
public void requestRemoveOpenOffer(String offerId, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
offerBookService.removeOffer(openOffers.get(offerId).getOffer(),
() -> {
if (openOffers.containsKey(offerId)) {
openOffers.remove(offerId);
persistOpenOffers();
resultHandler.handleResult();
}
else {
log.error("Locally stored offers does not contain the offer with the ID " + offerId);
errorMessageHandler.handleErrorMessage("Locally stored offers does not contain the offer with the ID " + offerId);
}
},
(message, throwable) -> errorMessageHandler.handleErrorMessage(message));
} }
/////////////////////////////////////////////////////////////////////////////////////////// public Trade onTakeOfferRequested(Coin amount, Offer offer) {
// Manage trades
///////////////////////////////////////////////////////////////////////////////////////////
public Trade createTrade(Offer offer) {
if (pendingTrades.containsKey(offer.getId()))
log.error("trades contains already an trade with the ID " + offer.getId());
Trade trade = new Trade(offer);
pendingTrades.put(offer.getId(), trade);
persistPendingTrades();
currentPendingTrade = trade;
return trade;
}
public void closeTrade(Trade trade) {
if (!pendingTrades.containsKey(trade.getId()))
log.error("trades does not contain the trade with the ID " + trade.getId());
pendingTrades.remove(trade.getId());
persistPendingTrades();
if (takerAsSellerProtocolMap.containsKey(trade.getId()))
takerAsSellerProtocolMap.remove(trade.getId());
else if (offererAsBuyerProtocolMap.containsKey(trade.getId()))
offererAsBuyerProtocolMap.remove(trade.getId());
closedTrades.put(trade.getId(), trade);
persistClosedTrades();
}
private void removeFailedTrade(Trade trade) {
if (!pendingTrades.containsKey(trade.getId()))
log.error("trades does not contain the trade with the ID " + trade.getId());
pendingTrades.remove(trade.getId());
persistPendingTrades();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Trading protocols
///////////////////////////////////////////////////////////////////////////////////////////
private void createOffererAsBuyerProtocol(OpenOffer openOffer) {
BuyerAsOffererModel model = new BuyerAsOffererModel(
openOffer,
tradeMessageService,
walletService,
blockChainService,
signatureService,
user);
openOffer.stateProperty().addListener((ov, oldValue, newValue) -> {
log.debug("trade state = " + newValue);
switch (newValue) {
case OPEN:
break;
case OFFER_ACCEPTED:
requestRemoveOpenOffer(openOffer.getId(),
() -> log.debug("remove offer was successful"),
(message) -> log.error(message));
Trade trade = model.getTrade();
pendingTrades.put(trade.getId(), trade);
persistPendingTrades();
currentPendingTrade = trade;
// TODO check, remove listener
trade.stateProperty().addListener((ov2, oldValue2, newValue2) -> {
log.debug("trade state = " + newValue);
switch (newValue2) {
case OPEN:
break;
case OFFERER_ACCEPTED: // only taker side
case DEPOSIT_PUBLISHED:
case DEPOSIT_CONFIRMED:
case FIAT_PAYMENT_STARTED:
case FIAT_PAYMENT_RECEIVED:
case PAYOUT_PUBLISHED:
persistPendingTrades();
break;
case OFFERER_REJECTED:
case FAILED:
removeFailedTrade(trade);
break;
default:
log.error("Unhandled trade state: " + newValue);
break;
}
});
break;
default:
log.error("Unhandled trade state: " + newValue);
break;
}
});
BuyerAsOffererProtocol buyerAcceptsOfferProtocol = new BuyerAsOffererProtocol(model);
offererAsBuyerProtocolMap.put(openOffer.getId(), buyerAcceptsOfferProtocol);
buyerAcceptsOfferProtocol.start();
}
public Trade requestTakeOffer(Coin amount, Offer offer) {
Trade trade = createTrade(offer); Trade trade = createTrade(offer);
trade.setTradeAmount(amount); trade.setTradeAmount(amount);
@ -353,60 +241,186 @@ public class TradeManager {
SellerAsTakerProtocol sellerTakesOfferProtocol = new SellerAsTakerProtocol(model); SellerAsTakerProtocol sellerTakesOfferProtocol = new SellerAsTakerProtocol(model);
takerAsSellerProtocolMap.put(trade.getId(), sellerTakesOfferProtocol); takerAsSellerProtocolMap.put(trade.getId(), sellerTakesOfferProtocol);
sellerTakesOfferProtocol.handleRequestTakeOfferUIEvent(); sellerTakesOfferProtocol.onTakeOfferRequested();
return trade; return trade;
} }
//TODO we don't support interruptions yet. public void onFiatPaymentStarted(String tradeId) {
// If the user has shut down the app we lose the offererAsBuyerProtocolMap // TODO remove if check when peristence is impl.
// Also we don't support yet offline messaging (mail box) if (offererAsBuyerProtocolMap.containsKey(tradeId)) {
public void fiatPaymentStarted(String tradeId) { offererAsBuyerProtocolMap.get(tradeId).onFiatPaymentStarted();
if (offererAsBuyerProtocolMap.get(tradeId) != null) {
offererAsBuyerProtocolMap.get(tradeId).handleBankTransferStartedUIEvent();
persistPendingTrades(); persistPendingTrades();
} }
else {
featureNotImplementedWarning.set("Sorry, you cannot continue. You have restarted the application in the " +
"meantime. Interruption of the trade process is not supported yet. Will need more time to be " +
"implemented.");
}
} }
public void fiatPaymentReceived(String tradeId) { public void onFiatPaymentReceived(String tradeId) {
takerAsSellerProtocolMap.get(tradeId).handleFiatReceivedUIEvent(); takerAsSellerProtocolMap.get(tradeId).onFiatPaymentReceived();
} }
public void requestIsOfferAvailable(Offer offer) {
if (!requestIsOfferAvailableProtocolMap.containsKey(offer.getId())) { public void onCloseTradeRequested(Trade trade) {
RequestIsOfferAvailableProtocol protocol = new RequestIsOfferAvailableProtocol(offer, tradeMessageService); closeTrade(trade, false);
requestIsOfferAvailableProtocolMap.put(offer.getId(), protocol);
protocol.start();
}
else {
log.warn("requestIsOfferAvailable already called for offer with ID:" + offer.getId());
}
} }
// When closing take offer view, we are not interested in the requestIsOfferAvailable result anymore, so remove from the map ///////////////////////////////////////////////////////////////////////////////////////////
public void stopRequestIsOfferAvailableRequest(Offer offer) { // Called from Offerbook (DHT)
requestIsOfferAvailableProtocolMap.remove(offer.getId()); ///////////////////////////////////////////////////////////////////////////////////////////
}
public void onOfferRemovedFromRemoteOfferBook(Offer offer) { public void onOfferRemovedFromRemoteOfferBook(Offer offer) {
requestIsOfferAvailableProtocolMap.remove(offer.getId()); requestIsOfferAvailableProtocolMap.remove(offer.getId());
} }
///////////////////////////////////////////////////////////////////////////////////////////
// Private
///////////////////////////////////////////////////////////////////////////////////////////
private OpenOffer createOpenOffer(Offer offer) {
OpenOffer openOffer = new OpenOffer(offer);
openOffers.put(openOffer.getId(), openOffer);
persistOpenOffers();
return openOffer;
}
private void removeOpenOffer(String offerId,
ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler,
boolean removeFromOffererAsBuyerProtocolMap) {
offerBookService.removeOffer(openOffers.get(offerId).getOffer(),
() -> {
if (openOffers.containsKey(offerId)) {
openOffers.remove(offerId);
persistOpenOffers();
if (removeFromOffererAsBuyerProtocolMap && offererAsBuyerProtocolMap.containsKey(offerId)) {
offererAsBuyerProtocolMap.get(offerId).cleanup();
offererAsBuyerProtocolMap.remove(offerId);
}
resultHandler.handleResult();
}
else {
log.error("Locally stored offers does not contain the offer with the ID " + offerId);
errorMessageHandler.handleErrorMessage("Locally stored offers does not contain the offer with the ID " + offerId);
}
},
(message, throwable) -> errorMessageHandler.handleErrorMessage(message));
}
private Trade createTrade(Offer offer) {
if (pendingTrades.containsKey(offer.getId()))
log.error("trades contains already an trade with the ID " + offer.getId());
Trade trade = new Trade(offer);
pendingTrades.put(offer.getId(), trade);
persistPendingTrades();
currentPendingTrade = trade;
return trade;
}
private void createOffererAsBuyerProtocol(OpenOffer openOffer) {
BuyerAsOffererModel model = new BuyerAsOffererModel(
openOffer,
tradeMessageService,
walletService,
blockChainService,
signatureService,
user);
openOffer.stateProperty().addListener((ov, oldValue, newValue) -> {
log.debug("trade state = " + newValue);
switch (newValue) {
case OPEN:
break;
case OFFER_ACCEPTED:
removeOpenOffer(openOffer.getId(),
() -> log.debug("remove offer was successful"),
(message) -> log.error(message),
false);
Trade trade = model.getTrade();
pendingTrades.put(trade.getId(), trade);
persistPendingTrades();
currentPendingTrade = trade;
// TODO check, remove listener
trade.stateProperty().addListener((ov2, oldValue2, newValue2) -> {
log.debug("trade state = " + newValue);
switch (newValue2) {
case OPEN:
break;
case OFFERER_ACCEPTED: // only taker side
case DEPOSIT_PUBLISHED:
case DEPOSIT_CONFIRMED:
case FIAT_PAYMENT_STARTED:
case FIAT_PAYMENT_RECEIVED:
case PAYOUT_PUBLISHED:
persistPendingTrades();
break;
case OFFERER_REJECTED:
case FAILED:
removeFailedTrade(trade);
offererAsBuyerProtocolMap.get(trade.getId()).cleanup();
break;
default:
log.error("Unhandled trade state: " + newValue);
break;
}
});
break;
default:
log.error("Unhandled trade state: " + newValue);
break;
}
});
BuyerAsOffererProtocol buyerAcceptsOfferProtocol = new BuyerAsOffererProtocol(model);
offererAsBuyerProtocolMap.put(openOffer.getId(), buyerAcceptsOfferProtocol);
}
private void removeFailedTrade(Trade trade) {
closeTrade(trade, true);
}
private void closeTrade(Trade trade, boolean failed) {
if (!pendingTrades.containsKey(trade.getId()))
log.error("trades does not contain the trade with the ID " + trade.getId());
pendingTrades.remove(trade.getId());
persistPendingTrades();
if (takerAsSellerProtocolMap.containsKey(trade.getId())) {
takerAsSellerProtocolMap.get(trade.getId()).cleanup();
takerAsSellerProtocolMap.remove(trade.getId());
}
else if (offererAsBuyerProtocolMap.containsKey(trade.getId())) {
offererAsBuyerProtocolMap.get(trade.getId()).cleanup();
offererAsBuyerProtocolMap.remove(trade.getId());
}
if (!failed) {
closedTrades.put(trade.getId(), trade);
persistClosedTrades();
}
else {
// TODO add failed trades to history
}
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Process new tradeMessages // Process new tradeMessages
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// TODO remove
// Routes the incoming messages to the responsible protocol // Routes the incoming messages to the responsible protocol
private void handleNewMessage(Message message, Peer sender) { private void handleNewMessage(Message message, Peer sender) {
log.trace("handleNewMessage: message = " + message.getClass().getSimpleName()); log.trace("handleNewMessage: message = " + message.getClass().getSimpleName());
log.trace("handleNewMessage: sender = " + sender); log.trace("handleNewMessage: sender = " + sender);
// TODO remove
if (message instanceof OfferMessage) { if (message instanceof OfferMessage) {
OfferMessage offerMessage = (OfferMessage) message; OfferMessage offerMessage = (OfferMessage) message;
// Before starting any take offer activity we check if the offer is still available. // Before starting any take offer activity we check if the offer is still available.
@ -441,10 +455,6 @@ public class TradeManager {
// Setters // Setters
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void setFeatureNotImplementedWarning(String featureNotImplementedWarning) {
this.featureNotImplementedWarning.set(featureNotImplementedWarning);
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Getters // Getters
@ -466,13 +476,6 @@ public class TradeManager {
return currentPendingTrade; return currentPendingTrade;
} }
public String getFeatureNotImplementedWarning() {
return featureNotImplementedWarning.get();
}
public StringProperty featureNotImplementedWarningProperty() {
return featureNotImplementedWarning;
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Private // Private

View file

@ -55,7 +55,7 @@ public class PlaceOfferProtocol {
this.offerBookService = offerBookService; this.offerBookService = offerBookService;
} }
public void placeOffer() { public void onPlaceOfferRequested() {
try { try {
validateOffer(); validateOffer();
Transaction transaction = createOfferFeeTx(); Transaction transaction = createOfferFeeTx();

View file

@ -45,15 +45,6 @@ import org.slf4j.LoggerFactory;
import static io.bitsquare.util.Validator.nonEmptyStringOf; import static io.bitsquare.util.Validator.nonEmptyStringOf;
/**
* Responsible for the correct execution of the sequence of tasks, message passing to the peer and message processing
* from the peer.
* <p/>
* This class handles the role of the offerer as the Bitcoin buyer.
* <p/>
* It uses sub tasks to not pollute the main class too much with all the async result/fault handling.
* Any data from incoming messages need to be validated before further processing.
*/
public class BuyerAsOffererProtocol { public class BuyerAsOffererProtocol {
private static final Logger log = LoggerFactory.getLogger(BuyerAsOffererProtocol.class); private static final Logger log = LoggerFactory.getLogger(BuyerAsOffererProtocol.class);
@ -67,6 +58,8 @@ public class BuyerAsOffererProtocol {
public BuyerAsOffererProtocol(BuyerAsOffererModel model) { public BuyerAsOffererProtocol(BuyerAsOffererModel model) {
this.model = model; this.model = model;
model.getTradeMessageService().addMessageHandler(this::handleMessage);
} }
@ -74,10 +67,6 @@ public class BuyerAsOffererProtocol {
// Public methods // Public methods
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void start() {
model.getTradeMessageService().addMessageHandler(this::handleMessage);
}
public void cleanup() { public void cleanup() {
model.getTradeMessageService().removeMessageHandler(this::handleMessage); model.getTradeMessageService().removeMessageHandler(this::handleMessage);
} }
@ -118,7 +107,7 @@ public class BuyerAsOffererProtocol {
BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model, BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model,
() -> { () -> {
log.debug("sequence0 completed"); log.debug("sequence at handleRequestTakeOfferMessage completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
@ -136,7 +125,7 @@ public class BuyerAsOffererProtocol {
BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model, BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model,
() -> { () -> {
log.debug("sequence1 completed"); log.debug("sequence at handleTakeOfferFeePayedMessage completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
@ -155,7 +144,7 @@ public class BuyerAsOffererProtocol {
BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model, BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model,
() -> { () -> {
log.debug("sequence2 completed"); log.debug("sequence at handleRequestOffererPublishDepositTxMessage completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
@ -174,14 +163,14 @@ public class BuyerAsOffererProtocol {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// UI event handling // Called from UI
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// User clicked the "bank transfer started" button // User clicked the "bank transfer started" button
public void handleBankTransferStartedUIEvent() { public void onFiatPaymentStarted() {
BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model, BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model,
() -> { () -> {
log.debug("sequence3 completed"); log.debug("sequence at handleBankTransferStartedUIEvent completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
@ -205,7 +194,7 @@ public class BuyerAsOffererProtocol {
BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model, BuyerAsOffererTaskRunner<BuyerAsOffererModel> sequence = new BuyerAsOffererTaskRunner<>(model,
() -> { () -> {
log.debug("sequence4 completed"); log.debug("sequence at handlePayoutTxPublishedMessage completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
@ -214,5 +203,4 @@ public class BuyerAsOffererProtocol {
sequence.addTasks(ProcessPayoutTxPublishedMessage.class); sequence.addTasks(ProcessPayoutTxPublishedMessage.class);
sequence.run(); sequence.run();
} }
} }

View file

@ -48,13 +48,6 @@ import org.slf4j.LoggerFactory;
import static io.bitsquare.util.Validator.nonEmptyStringOf; import static io.bitsquare.util.Validator.nonEmptyStringOf;
/**
* Responsible for the correct execution of the sequence of tasks, message passing to the peer and message processing
* from the peer.
* That class handles the role of the taker as the Bitcoin seller.
* It uses sub tasks to not pollute the main class too much with all the async result/fault handling.
* Any data from incoming messages as well data used to send to the peer need to be validated before further processing.
*/
public class SellerAsTakerProtocol { public class SellerAsTakerProtocol {
private static final Logger log = LoggerFactory.getLogger(SellerAsTakerProtocol.class); private static final Logger log = LoggerFactory.getLogger(SellerAsTakerProtocol.class);
@ -71,15 +64,15 @@ public class SellerAsTakerProtocol {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// UI event handling // Called from UI
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void handleRequestTakeOfferUIEvent() { public void onTakeOfferRequested() {
model.getTradeMessageService().addMessageHandler(this::handleMessage); model.getTradeMessageService().addMessageHandler(this::handleMessage);
SellerAsTakerTaskRunner<SellerAsTakerModel> sequence = new SellerAsTakerTaskRunner<>(model, SellerAsTakerTaskRunner<SellerAsTakerModel> sequence = new SellerAsTakerTaskRunner<>(model,
() -> { () -> {
log.debug("sequence1 completed"); log.debug("sequence at handleRequestTakeOfferUIEvent completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
@ -128,96 +121,96 @@ public class SellerAsTakerProtocol {
private void handleRespondToTakeOfferRequestMessage(RespondToTakeOfferRequestMessage tradeMessage) { private void handleRespondToTakeOfferRequestMessage(RespondToTakeOfferRequestMessage tradeMessage) {
model.setTradeMessage(tradeMessage); model.setTradeMessage(tradeMessage);
SellerAsTakerTaskRunner<SellerAsTakerModel> sequence2 = new SellerAsTakerTaskRunner<>(model, SellerAsTakerTaskRunner<SellerAsTakerModel> sequence = new SellerAsTakerTaskRunner<>(model,
() -> { () -> {
log.debug("sequence2 completed"); log.debug("sequence at handleRespondToTakeOfferRequestMessage completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
} }
); );
sequence2.addTasks( sequence.addTasks(
ProcessRespondToTakeOfferRequestMessage.class, ProcessRespondToTakeOfferRequestMessage.class,
PayTakeOfferFee.class, PayTakeOfferFee.class,
SendTakeOfferFeePayedMessage.class SendTakeOfferFeePayedMessage.class
); );
sequence2.run(); sequence.run();
} }
private void handleTakerDepositPaymentRequestMessage(TakerDepositPaymentRequestMessage tradeMessage) { private void handleTakerDepositPaymentRequestMessage(TakerDepositPaymentRequestMessage tradeMessage) {
model.setTradeMessage(tradeMessage); model.setTradeMessage(tradeMessage);
SellerAsTakerTaskRunner<SellerAsTakerModel> sequence3 = new SellerAsTakerTaskRunner<>(model, SellerAsTakerTaskRunner<SellerAsTakerModel> sequence = new SellerAsTakerTaskRunner<>(model,
() -> { () -> {
log.debug("sequence3 completed"); log.debug("sequence at handleTakerDepositPaymentRequestMessage completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
} }
); );
sequence3.addTasks( sequence.addTasks(
ProcessTakerDepositPaymentRequestMessage.class, ProcessTakerDepositPaymentRequestMessage.class,
VerifyOffererAccount.class, VerifyOffererAccount.class,
CreateAndSignContract.class, CreateAndSignContract.class,
PayDeposit.class, PayDeposit.class,
SendSignedTakerDepositTxAsHex.class SendSignedTakerDepositTxAsHex.class
); );
sequence3.run(); sequence.run();
} }
private void handleDepositTxPublishedMessage(DepositTxPublishedMessage tradeMessage) { private void handleDepositTxPublishedMessage(DepositTxPublishedMessage tradeMessage) {
model.setTradeMessage(tradeMessage); model.setTradeMessage(tradeMessage);
SellerAsTakerTaskRunner<SellerAsTakerModel> sequence4 = new SellerAsTakerTaskRunner<>(model, SellerAsTakerTaskRunner<SellerAsTakerModel> sequence = new SellerAsTakerTaskRunner<>(model,
() -> { () -> {
log.debug("sequence4 completed"); log.debug("sequence at handleDepositTxPublishedMessage completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
} }
); );
sequence4.addTasks( sequence.addTasks(
ProcessDepositTxPublishedMessage.class, ProcessDepositTxPublishedMessage.class,
TakerCommitDepositTx.class TakerCommitDepositTx.class
); );
sequence4.run(); sequence.run();
} }
private void handleBankTransferInitedMessage(BankTransferInitedMessage tradeMessage) { private void handleBankTransferInitedMessage(BankTransferInitedMessage tradeMessage) {
model.setTradeMessage(tradeMessage); model.setTradeMessage(tradeMessage);
SellerAsTakerTaskRunner<SellerAsTakerModel> sequence5 = new SellerAsTakerTaskRunner<>(model, SellerAsTakerTaskRunner<SellerAsTakerModel> sequence = new SellerAsTakerTaskRunner<>(model,
() -> { () -> {
log.debug("sequence5 completed"); log.debug("sequence at handleBankTransferInitedMessage completed");
model.getTrade().setState(Trade.State.FIAT_PAYMENT_STARTED); model.getTrade().setState(Trade.State.FIAT_PAYMENT_STARTED);
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
} }
); );
sequence5.addTasks(ProcessBankTransferInitedMessage.class); sequence.addTasks(ProcessBankTransferInitedMessage.class);
sequence5.run(); sequence.run();
} }
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// UI event handling // Called from UI
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// User clicked the "bank transfer received" button, so we release the funds for pay out // User clicked the "bank transfer received" button, so we release the funds for pay out
public void handleFiatReceivedUIEvent() { public void onFiatPaymentReceived() {
SellerAsTakerTaskRunner<SellerAsTakerModel> sequence6 = new SellerAsTakerTaskRunner<>(model, SellerAsTakerTaskRunner<SellerAsTakerModel> sequence = new SellerAsTakerTaskRunner<>(model,
() -> { () -> {
log.debug("sequence6 completed"); log.debug("sequence at handleFiatReceivedUIEvent completed");
}, },
(message, throwable) -> { (message, throwable) -> {
log.error(message); log.error(message);
} }
); );
sequence6.addTasks( sequence.addTasks(
SignAndPublishPayoutTx.class, SignAndPublishPayoutTx.class,
VerifyOfferFeePayment.class, VerifyOfferFeePayment.class,
SendPayoutTxToOfferer.class SendPayoutTxToOfferer.class
); );
sequence6.run(); sequence.run();
} }
} }

View file

@ -277,7 +277,7 @@ public class PlaceOfferProtocolTest {
countDownLatch.countDown(); countDownLatch.countDown();
}; };
PlaceOfferProtocol placeOfferProtocol = getPlaceOfferProtocol(getOffer(), resultHandler, faultHandler); PlaceOfferProtocol placeOfferProtocol = getPlaceOfferProtocol(getOffer(), resultHandler, faultHandler);
placeOfferProtocol.placeOffer(); placeOfferProtocol.onPlaceOfferRequested();
countDownLatch.await(); countDownLatch.await();
} }