下面列出了io.reactivex.Single#blockingGet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public SingleSource<Wallet> apply(Single<Wallet> upstream) {
Wallet wallet = upstream.blockingGet();
return Single.fromCallable(() -> wallet);
// return passwordStore
// .setPassword(wallet, password)
// .onErrorResumeNext(err -> walletRepository.deleteWallet(wallet.getAddress())
// .lift(observer -> new DisposableCompletableObserver() {
// @Override
// public void onComplete() {
// observer.onError(err);
// }
//
// @Override
// public void onError(Throwable e) {
// observer.onError(e);
// }
// }))
// .toSingle(() -> wallet);
}
@Test
public void whenCreateIsCalledAndAnErrorOccursThenObserverOnErrorIsCalled()
throws Throwable {
this.expectedException.expectCause(isA(MqttException.class));
final IMqttAsyncClient client = Mockito.mock(IMqttAsyncClient.class);
Mockito.when(client.publish(Matchers.any(String.class),
Matchers.any(byte[].class), Matchers.any(int.class),
Matchers.any(boolean.class), Matchers.isNull(),
Matchers.any(PublishFactory.PublishActionListener.class)))
.thenThrow(new MqttException(
MqttException.REASON_CODE_CLIENT_CONNECTED));
final PublishFactory factory = new PublishFactory(client);
final Single<PublishToken> obs = factory.create("topic1",
Mockito.mock(MqttMessage.class));
obs.blockingGet();
}
@Test
public void testRemoveListenerById() throws InterruptedException {
RTopicRx topic1 = redisson.getTopic("topic1");
MessageListener listener = new MessageListener() {
@Override
public void onMessage(CharSequence channel, Object msg) {
Assert.fail();
}
};
Single<Integer> res = topic1.addListener(Message.class, listener);
Integer listenerId = res.blockingGet();
topic1 = redisson.getTopic("topic1");
topic1.removeListener(listenerId);
topic1.publish(new Message("123"));
}
@Test
public void deployVerticleWithOptions() throws Exception {
CoreVerticle verticle = new CoreVerticle();
JsonObject expected = new JsonObject()
.put("bim", 1).put("bam", new JsonArray().add(1).add(2).add(3)).put("boum", new JsonObject().put("toto", "titi"));
Single<String> single = RxHelper.deployVerticle(vertx, verticle, new DeploymentOptions().setConfig(expected));
assertNull(verticle.config);
single.blockingGet();
assertEquals(expected, verticle.config);
}
@Override
protected Exception getFailure(Single instance) {
AtomicReference<Exception> reference = new AtomicReference<>();
try {
//noinspection ResultOfMethodCallIgnored
instance.blockingGet();
} catch (Exception e) {
reference.set(e);
}
return reference.get();
}
@Test
public void deployVerticleFailure() throws Exception {
CoreVerticle verticle = new CoreVerticle(true);
Single<String> single = RxHelper.deployVerticle(vertx, verticle);
assertNull(verticle.config);
try {
single.blockingGet();
fail("Verticle deployment should fail");
} catch (RuntimeException e) {
assertThat(e.getCause(), instanceOf(MyException.class));
assertNotNull(verticle.config);
assertTrue(verticle.config.isEmpty());
}
}
@Test
public void deployVerticle() throws Exception {
CoreVerticle verticle = new CoreVerticle();
Single<String> single = RxHelper.deployVerticle(vertx, verticle);
assertNull(verticle.config);
single.blockingGet();
assertNotNull(verticle.config);
assertTrue(verticle.config.isEmpty());
}
@Test
public void shouldDelegateToOtherAdapter() {
String body = "this is from rxjava";
stubFor(get(urlPathEqualTo("/delegated"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/plain")
.withBody(body)));
RetrofitService service = new Retrofit.Builder()
.addCallAdapterFactory(RateLimiterCallAdapter.of(RateLimiter.of(
"backendName",
RateLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(50))
.limitForPeriod(1)
.limitRefreshPeriod(Duration.ofDays(1))
.build()
)))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.baseUrl(wireMockRule.baseUrl())
.build()
.create(RetrofitService.class);
Single<String> success = service.delegated();
Single<String> failure = service.delegated();
String resultBody = success.blockingGet();
try {
failure.blockingGet();
fail("Expected HttpException to be thrown");
} catch (HttpException httpe) {
assertThat(httpe.code()).isEqualTo(429);
}
assertThat(resultBody).isEqualTo(body);
verify(1, getRequestedFor(urlPathEqualTo("/delegated")));
}
@Test
public void shouldNotDelegateToOtherAdapterWhenAddedAfterwards() {
String body = "this is from rxjava";
stubFor(get(urlPathEqualTo("/delegated"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/plain")
.withBody(body)));
RetrofitService service = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addCallAdapterFactory(RateLimiterCallAdapter.of(RateLimiter.of(
"backendName",
RateLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(50))
.limitForPeriod(1)
.limitRefreshPeriod(Duration.ofDays(1))
.build()
)))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.baseUrl(wireMockRule.baseUrl())
.build()
.create(RetrofitService.class);
Single<String> success = service.delegated();
Single<String> failure = service.delegated();
String resultBody = success.blockingGet();
failure.blockingGet();
assertThat(resultBody).isEqualTo(body);
verify(2, getRequestedFor(urlPathEqualTo("/delegated")));
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == calcelButton) {
setVisible(false);
}
if(e.getSource() == okButton || e.getSource() == pin) {
String error = null;
Globals g = Globals.getInstance();
if(error == null && !acceptBox.isSelected()) {
error = tr("dlg_accept_first");
acceptBox.requestFocus();
}
if(error == null && !g.usingLedger() && !g.checkPIN(pin.getPassword())) {
error = tr("dlg_invalid_pin");
pin.requestFocus();
}
if(error!=null) {
Toast.makeText((JFrame) this.getOwner(), error, Toast.Style.ERROR).display(okButton);
return;
}
// all set, lets cancel the order
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
Single<byte[]> utx = null;
if(isToken) {
if(order.getType() == AssetOrder.OrderType.BID)
utx = g.getNS().generateCancelBidOrderTransaction(g.getPubKey(), order.getId(),
suggestedFee.getPriorityFee(), 1440);
else
utx = g.getNS().generateCancelAskOrderTransaction(g.getPubKey(), order.getId(),
suggestedFee.getPriorityFee(), 1440);
}
else {
// update the security to zero to withdraw all funds
byte[] message = BT.callMethodMessage(state.getMethod("update"), 0L);
BurstValue amountToSend = BurstValue.fromPlanck(state.getActivationFee());
utx = g.getNS().generateTransactionWithMessage(state.getAddress(), g.getPubKey(),
amountToSend, suggestedFee.getPriorityFee(),
Constants.BURST_DEADLINE, message);
}
unsigned = utx.blockingGet();
if(g.usingLedger()) {
LedgerService.getInstance().requestSign(unsigned, null, g.getLedgerIndex());
okButton.setEnabled(false);
Toast.makeText((JFrame) this.getOwner(), tr("ledger_authorize"), Toast.Style.NORMAL).display(okButton);
return;
}
byte[] signedTransactionBytes = g.signTransaction(pin.getPassword(), unsigned);
reportSigned(signedTransactionBytes, null);
}
catch (Exception ex) {
ex.printStackTrace();
Toast.makeText((JFrame) this.getOwner(), ex.getCause().getMessage(), Toast.Style.ERROR).display(okButton);
}
setCursor(Cursor.getDefaultCursor());
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cancelButton) {
setVisible(false);
}
if(e.getSource() == okButton || e.getSource() == pin) {
String error = null;
Globals g = Globals.getInstance();
if(error == null && !acceptBox.isSelected()) {
error = tr("dlg_accept_first");
acceptBox.requestFocus();
}
if(error == null && !g.checkPIN(pin.getPassword())) {
error = tr("dlg_invalid_pin");
pin.requestFocus();
}
if(error!=null) {
Toast.makeText((JFrame) this.getOwner(), error, Toast.Style.ERROR).display(okButton);
return;
}
// all set, lets register the contract
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
int ncontracts = Integer.parseInt(numOfContractsSpinner.getValue().toString());
for (int c = 0; c < ncontracts; c++) {
long data[] = Contracts.getNewContractData(g.isTestnet());
ByteBuffer dataBuffer = ByteBuffer.allocate(data==null ? 0 : data.length*8);
dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; data!=null && i < data.length; i++) {
dataBuffer.putLong(data[i]);
}
byte[] creationBytes = BurstCrypto.getInstance().getATCreationBytes((short)2,
contract.getCode(), dataBuffer.array(), (short)contract.getDataPages(), (short)1, (short)1,
BurstValue.fromPlanck(SellContract.ACTIVATION_FEE));
Single<TransactionBroadcast> tx = g.getNS().generateCreateATTransaction(g.getPubKey(),
BT.getMinRegisteringFee(contract),
Constants.BURST_DEADLINE, "BTDEX", "BTDEX sell contract " + System.currentTimeMillis(), creationBytes)
.flatMap(unsignedTransactionBytes -> {
byte[] signedTransactionBytes = g.signTransaction(pin.getPassword(), unsignedTransactionBytes);
return g.getNS().broadcastTransaction(signedTransactionBytes);
});
TransactionBroadcast tb = tx.blockingGet();
tb.getTransactionId();
setVisible(false);
Toast.makeText((JFrame) this.getOwner(),
tr("send_tx_broadcast", tb.getTransactionId().toString()), Toast.Style.SUCCESS).display();
}
}
catch (Exception ex) {
Toast.makeText((JFrame) this.getOwner(), ex.getMessage(), Toast.Style.ERROR).display(okButton);
}
setCursor(Cursor.getDefaultCursor());
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cancelButton) {
setVisible(false);
}
if(e.getSource()==buyToken || e.getSource()==sellToken) {
buyToken.setBackground(buyToken.isSelected() ? HistoryPanel.GREEN : this.getBackground());
sellToken.setBackground(sellToken.isSelected() ? HistoryPanel.RED : this.getBackground());
okButton.setText(tr(buyToken.isSelected() ? "offer_confirm_limit_buy" : "offer_confirm_limit_sell"));
okButton.setBackground(buyToken.isSelected() ? HistoryPanel.GREEN : HistoryPanel.RED);
somethingChanged();
}
if(e.getSource() == okButton || e.getSource() == pinField) {
String error = null;
Globals g = Globals.getInstance();
if(error == null && (priceValue == null || priceValue.longValue() <= 0)) {
error = tr("offer_invalid_price");
}
if(error == null && (amountValue == null || amountValue.longValue() <= 0)) {
error = tr("send_invalid_amount");
}
if(error == null && !acceptBox.isSelected()) {
error = tr("dlg_accept_first");
acceptBox.requestFocus();
}
if(error == null && !g.usingLedger() && !g.checkPIN(pinField.getPassword())) {
error = tr("dlg_invalid_pin");
pinField.requestFocus();
}
if(error!=null) {
Toast.makeText((JFrame) this.getOwner(), error, Toast.Style.ERROR).display(okButton);
return;
}
if(g.usingLedger()) {
if(BurstLedger.isAppAvailable())
Toast.makeText((JFrame) this.getOwner(), tr("ledger_auth"), Toast.Style.NORMAL).display(okButton);
else {
Toast.makeText((JFrame) this.getOwner(), tr("ledger_error"), Toast.Style.ERROR).display(okButton);
return;
}
}
// all set, lets place the order
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Single<byte[]> utx = null;
if(sellToken.isSelected())
utx = g.getNS().generatePlaceAskOrderTransaction(g.getPubKey(), market.getTokenID(),
amountValue, priceValue, suggestedFee, Constants.BURST_DEADLINE);
else
utx = g.getNS().generatePlaceBidOrderTransaction(g.getPubKey(), market.getTokenID(),
amountValue, priceValue, suggestedFee, Constants.BURST_DEADLINE);
unsigned = utx.blockingGet();
if(g.usingLedger()) {
LedgerService.getInstance().requestSign(unsigned, null, g.getLedgerIndex());
okButton.setEnabled(false);
priceField.setEnabled(false);
amountField.setEnabled(false);
Toast.makeText((JFrame) this.getOwner(), tr("ledger_authorize"), Toast.Style.NORMAL).display(okButton);
return;
}
byte[] signedTransactionBytes = g.signTransaction(pinField.getPassword(), unsigned);
reportSigned(signedTransactionBytes, null);
}
catch (Exception ex) {
ex.printStackTrace();
Toast.makeText((JFrame) this.getOwner(), ex.getCause().getMessage(), Toast.Style.ERROR).display(okButton);
}
setCursor(Cursor.getDefaultCursor());
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cancelButton) {
setVisible(false);
return;
}
if(e.getSource() == acceptOtherTermsBox) {
if(acceptOtherTermsBox.isSelected()) {
yourAmountOtherSlider.setValue(otherAmountOtherSlider.getValue());;
yourAmountYouSlider.setValue(otherAmountYouSlider.getValue());
}
yourAmountOtherSlider.setEnabled(!acceptOtherTermsBox.isSelected());
yourAmountYouSlider.setEnabled(!acceptOtherTermsBox.isSelected());
}
if(e.getSource() == okButton || e.getSource() == pinField) {
String error = null;
Component errorComp = null;
Globals g = Globals.getInstance();
if(error == null) {
// check if something changed
// if(priceValue.longValue() == contract.getRate() &&
// (accountDetails.getText().length()==0 ||
// accountDetails.getText().equals(contract.getMarketAccount()))
// )
// error = tr("offer_no_changes");
}
if(error == null && !acceptBox.isSelected()) {
error = tr("dlg_accept_first");
errorComp = acceptBox;
acceptBox.requestFocus();
}
if(error == null && !g.checkPIN(pinField.getPassword())) {
error = tr("dlg_invalid_pin");
pinField.requestFocus();
}
if(error!=null) {
Toast.makeText((JFrame) this.getOwner(), error, Toast.Style.ERROR).display(errorComp != null ? errorComp : okButton);
return;
}
// all set, lets place the dispute update
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
long amountToCreator = amount * (isCreator ? yourAmountYouSlider.getValue() : yourAmountOtherSlider.getValue()) / 100;
long amountToTaker = amount - amountToCreator;
// we are sending the dispute message with our amounts
byte[] message = BT.callMethodMessage(contract.getMethod("dispute"), amountToCreator, amountToTaker);
BurstValue amountToSend = BurstValue.fromPlanck(contract.getActivationFee());
Single<byte[]> utx = g.getNS().generateTransactionWithMessage(contract.getAddress(), g.getPubKey(),
amountToSend, suggestedFee,
Constants.BURST_DEADLINE, message);
Single<TransactionBroadcast> tx = utx.flatMap(unsignedTransactionBytes -> {
byte[] signedTransactionBytes = g.signTransaction(pinField.getPassword(), unsignedTransactionBytes);
return g.getNS().broadcastTransaction(signedTransactionBytes);
});
TransactionBroadcast tb = tx.blockingGet();
tb.getTransactionId();
setVisible(false);
Toast.makeText((JFrame) this.getOwner(),
tr("send_tx_broadcast", tb.getTransactionId().toString()), Toast.Style.SUCCESS).display();
}
catch (Exception ex) {
ex.printStackTrace();
Toast.makeText((JFrame) this.getOwner(), ex.getCause().getMessage(), Toast.Style.ERROR).display(okButton);
}
setCursor(Cursor.getDefaultCursor());
}
}
@Test
public void shouldLog() throws Exception {
setLogLevel(Level.TRACE);
IceCreamOrder order = new OrderGenerator().generate(20);
Bill billExpected = Bill.makeBill(order);
wireMockRule.stubFor(post(urlEqualTo("/icecream/orders"))
.withRequestBody(equalTo(TestUtils.MAPPER.writeValueAsString(order)))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(TestUtils.MAPPER.writeValueAsString(billExpected))));
IcecreamServiceApi client = builder()
.target(IcecreamServiceApi.class,
"http://localhost:" + wireMockRule.port());
Single<Bill> billMono = client.makeOrder(order);
// no logs before subscription
ArgumentCaptor<LogEvent> argumentCaptor = ArgumentCaptor.forClass(LogEvent.class);
Mockito.verify(appender, never()).append(argumentCaptor.capture());
billMono.blockingGet();
Mockito.verify(appender, times(7)).append(argumentCaptor.capture());
List<LogEvent> logEvents = argumentCaptor.getAllValues();
assertLogEvent(logEvents, 0, Level.DEBUG,
"[IcecreamServiceApi#makeOrder]--->POST http://localhost");
assertLogEvent(logEvents, 1, Level.TRACE,
"[IcecreamServiceApi#makeOrder] REQUEST HEADERS\n" +
"Accept:[application/json]");
assertLogEvent(logEvents, 2, Level.TRACE,
"[IcecreamServiceApi#makeOrder] REQUEST BODY\n" +
"IceCreamOrder{ id=20, balls=");
assertLogEvent(logEvents, 3, Level.TRACE,
"[IcecreamServiceApi#makeOrder] RESPONSE HEADERS\n" +
"Content-Type:application/json");
assertLogEvent(logEvents, 4, Level.DEBUG,
"[IcecreamServiceApi#makeOrder]<--- headers takes");
assertLogEvent(logEvents, 5, Level.TRACE,
"[IcecreamServiceApi#makeOrder] RESPONSE BODY\n" +
"reactivefeign.rx2.testcase.domain.Bill");
assertLogEvent(logEvents, 6, Level.DEBUG,
"[IcecreamServiceApi#makeOrder]<--- body takes");
}
@SuppressWarnings("unchecked")
@Override
protected String getOne(Single instance) {
Single<String> single = instance.cast(String.class);
return single.blockingGet();
}
@SuppressWarnings("unchecked")
@Override
protected String getOne(Single instance) {
Single<String> single = instance.cast(String.class);
return single.blockingGet();
}
@Override
protected void consume(Single instance) {
instance.blockingGet();
}
@Override public Object adaptResponse(Object response, Metadata<Rx2Retrofit> metadata) {
checkReturnMethodTypeIsSingleOrCompletable(metadata);
if (response instanceof Completable) return null;
Single single = (Single) response;
Object payload = single.blockingGet();
if (payload instanceof Response) {
Object body = ((Response) payload).body();
return body;
}
return payload;
}
public static <T> T execute(Single<T> single) {
return single.blockingGet();
}
public static <V> V sync(Single<V> single) {
return single.blockingGet();
}