io.reactivex.Single Java Examples
The following examples show how to use
io.reactivex.Single.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WalletRepository.java From alpha-wallet-android with MIT License | 6 votes |
@Override public Single<BigDecimal> balanceInWei(Wallet wallet) { return Single.fromCallable(() -> { try { return new BigDecimal(getWeb3jService(networkRepository.getDefaultNetwork().chainId) .ethGetBalance(wallet.address, DefaultBlockParameterName.PENDING) .send() .getBalance()); } catch (IOException e) { return BigDecimal.valueOf(-1); } }).subscribeOn(Schedulers.io()); }
Example #2
Source File: UserServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Override public Single<ListResponse<User>> list(int page, int size, String baseUrl) { LOGGER.debug("Find users by domain: {}", domain.getId()); return userRepository.findByDomain(domain.getId(), page, size) .flatMap(userPage -> { // A negative value SHALL be interpreted as "0". // A value of "0" indicates that no resource results are to be returned except for "totalResults". if (size <= 0) { return Single.just(new ListResponse<User>(null, userPage.getCurrentPage() + 1, userPage.getTotalCount(), 0)); } else { // SCIM use 1-based index (increment current page) return Observable.fromIterable(userPage.getData()) .map(user1 -> convert(user1, baseUrl, true)) // set groups .flatMapSingle(user1 -> setGroups(user1)) .toList() .map(users -> new ListResponse<>(users, userPage.getCurrentPage() + 1, userPage.getTotalCount(), users.size())); } }) .onErrorResumeNext(ex -> { LOGGER.error("An error occurs while trying to find users by domain {}", domain, ex); return Single.error(new TechnicalManagementException(String.format("An error occurs while trying to find users by domain %s", domain), ex)); }); }
Example #3
Source File: OperatorActivity.java From android-open-framework-analysis with Apache License 2.0 | 6 votes |
private void single() { Single.just(1).subscribe(new SingleObserver<Integer>() { @Override public void onSubscribe(Disposable d) { Log.d(TAG, "onSubscribe: " + d.isDisposed()); } @Override public void onSuccess(Integer integer) { Log.d(TAG, "onSuccess: " + integer); } @Override public void onError(Throwable e) { } }); }
Example #4
Source File: PermissionTicketServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_errorMultipleResource_missingScope() { //Prepare request List<PermissionRequest> request = Arrays.asList( new PermissionRequest().setResourceId("one").setResourceScopes(Arrays.asList("a","b")), new PermissionRequest().setResourceId("two").setResourceScopes(Arrays.asList("c","d")) ); // Prepare Resource List<Resource> found = Arrays.asList( new Resource().setId("one").setResourceScopes(Arrays.asList("a","b")), new Resource().setId("two").setResourceScopes(Arrays.asList("not","same")) ); when(resourceService.findByDomainAndClientAndResources(DOMAIN_ID, CLIENT_ID,Arrays.asList("one","two"))).thenReturn(Single.just(found)); TestObserver<PermissionTicket> testObserver = service.create(request, DOMAIN_ID, CLIENT_ID).test(); testObserver.assertNotComplete(); testObserver.assertError(err -> ((InvalidPermissionRequestException)err).getOAuth2ErrorCode().equals("invalid_scope")); verify(repository, times(0)).create(any()); }
Example #5
Source File: ApplicationServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Override public Single<Set<TopApplication>> findTopApplications() { LOGGER.debug("Find top applications"); return applicationRepository.findAll(0, Integer.MAX_VALUE) .flatMapObservable(pagedApplications -> Observable.fromIterable(pagedApplications.getData())) .flatMapSingle(application -> tokenService.findTotalTokensByApplication(application) .map(totalToken -> { TopApplication topApplication = new TopApplication(); topApplication.setApplication(application); topApplication.setAccessTokens(totalToken.getTotalAccessTokens()); return topApplication; }) ) .toList() .map(topApplications -> topApplications.stream().filter(topClient -> topClient.getAccessTokens() > 0).collect(Collectors.toSet())) .onErrorResumeNext(ex -> { LOGGER.error("An error occurs while trying to find top applications", ex); return Single.error(new TechnicalManagementException("An error occurs while trying to find top applications", ex)); }); }
Example #6
Source File: DynamicClientRegistrationServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_sectorIdentifierUriBadRequest() { final String sectorUri = "https://sector/uri"; DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest(); request.setRedirectUris(Optional.empty()); request.setSectorIdentifierUri(Optional.of(sectorUri));//fail due to invalid url HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); when(webClient.getAbs(sectorUri)).thenReturn(httpRequest); when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test(); testObserver.assertError(InvalidClientMetadataException.class); testObserver.assertNotComplete(); assertTrue("Should have only one exception", testObserver.errorCount()==1); assertTrue("Unexpected start of error message", testObserver.errors().get(0).getMessage().startsWith("Unable to parse sector_identifier_uri")); }
Example #7
Source File: TokenEndpointTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void shouldInvokeTokenEndpoint_withValidClientCredentials_noAccessToken() throws Exception { Client client = new Client(); client.setClientId("my-client"); client.setScopes(Collections.singletonList("read")); router.route().order(-1).handler(new Handler<RoutingContext>() { @Override public void handle(RoutingContext routingContext) { routingContext.put("client", client); routingContext.next(); } }); when(tokenGranter.grant(any(TokenRequest.class), any(io.gravitee.am.model.oidc.Client.class))).thenReturn(Single.error(new Exception())); testRequest( HttpMethod.POST, "/oauth/token?client_id=my-client&client_secret=my-secret&grant_type=client_credentials", HttpStatusCode.INTERNAL_SERVER_ERROR_500, "Internal Server Error"); }
Example #8
Source File: ClientCalls.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Implements a unary → stream call as {@link Single} → {@link Flowable}, where the server responds with a * stream of messages. */ public static <TRequest, TResponse> Flowable<TResponse> oneToMany( final Single<TRequest> rxRequest, final BiConsumer<TRequest, StreamObserver<TResponse>> delegate, final CallOptions options) { try { final int prefetch = RxCallOptions.getPrefetch(options); final int lowTide = RxCallOptions.getLowTide(options); return rxRequest .flatMapPublisher(new io.reactivex.functions.Function<TRequest, Publisher<? extends TResponse>>() { @Override public Publisher<? extends TResponse> apply(TRequest request) { final RxClientStreamObserverAndPublisher<TResponse> consumerStreamObserver = new RxClientStreamObserverAndPublisher<TResponse>(null, null, prefetch, lowTide); delegate.accept(request, consumerStreamObserver); return consumerStreamObserver; } }); } catch (Throwable throwable) { return Flowable.error(throwable); } }
Example #9
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@Path("coroutines/1") @GET public Single<Response> helloAsync(@Context io.vertx.reactivex.core.Vertx rxVertx){ return Fibers.fiber(() -> { System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); System.err.println("Got response"); HttpResponse<io.vertx.reactivex.core.buffer.Buffer> httpResponse = Fibers.await(responseHandler); System.err.println("Got body"); client.close(); return Response.ok(httpResponse.body().toString()).build(); }); }
Example #10
Source File: AuditVerticle.java From vertx-kubernetes-workshop with Apache License 2.0 | 6 votes |
private void storeInDatabase(JsonObject operation) { // 1. need to retrieve a connection // 2. execute the insertion statement // 3. close the connection // Step 1 get the connection Single<SQLConnection> connectionRetrieved = jdbc.rxGetConnection(); // Step 2, when the connection is retrieved (this may have failed), do the insertion (upon success) Single<UpdateResult> update = connectionRetrieved .flatMap(connection -> connection.rxUpdateWithParams(INSERT_STATEMENT, new JsonArray().add(operation.encode())) // Step 3, when the insertion is done, close the connection. .doAfterTerminate(connection::close)); update.subscribe(result -> { // Ok }, err -> { System.err.println("Failed to insert operation in database: " + err); }); }
Example #11
Source File: DomainServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void shouldUpdate() { UpdateDomain updateDomain = Mockito.mock(UpdateDomain.class); when(domainRepository.findById("my-domain")).thenReturn(Maybe.just(new Domain())); when(domainRepository.update(any(Domain.class))).thenReturn(Single.just(new Domain())); when(eventService.create(any())).thenReturn(Single.just(new Event())); TestObserver testObserver = domainService.update("my-domain", updateDomain).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); verify(domainRepository, times(1)).findById(anyString()); verify(domainRepository, times(1)).update(any(Domain.class)); verify(eventService, times(1)).create(any()); }
Example #12
Source File: StarredViewModel.java From mvvm-template with GNU General Public License v3.0 | 6 votes |
@Override protected void callApi(int page, OnCallApiDone<Repo> onCallApiDone) { Single<Pageable<Repo>> single; if (staredCount != null && (staredCount.getValue() == null || staredCount.getValue() < 0)) { single = Single.zip(userRestService.getStarred(targetUser, page), userRestService.getStarredCount(targetUser), (repoPageable, count) -> { if (count != null){ staredCount.setValue(count.getLast()); } return repoPageable; }); } else { single = userRestService.getStarred(targetUser, page); } execute(true, single, repoPageable -> { onCallApiDone.onDone(repoPageable.getLast(), page == 1, repoPageable.getItems()); }); }
Example #13
Source File: UserServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void shouldDelete() { User user = new User(); user.setReferenceType(ReferenceType.DOMAIN); user.setReferenceId(DOMAIN); when(userRepository.findById("my-user")).thenReturn(Maybe.just(user)); when(userRepository.delete("my-user")).thenReturn(Completable.complete()); when(eventService.create(any())).thenReturn(Single.just(new Event())); TestObserver testObserver = userService.delete("my-user").test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); verify(userRepository, times(1)).delete("my-user"); verify(eventService, times(1)).create(any()); }
Example #14
Source File: AsyncRXQueryExecutor.java From vertx-jooq with MIT License | 6 votes |
@Override @SuppressWarnings("unchecked") public Single<T> insertReturning(Function<DSLContext, ? extends InsertResultStep<R>> queryFunction, Function<Object, T> keyMapper) { Query query = createQuery(queryFunction); log(query); String sql = query.getSQL(); JsonArray bindValues = getBindValues(query); Function<SQLConnection, Single<? extends T>> runInsertReturning; if(isMysql){ runInsertReturning = sqlConnection -> sqlConnection .rxUpdateWithParams(sql, bindValues) .map(updateResult -> keyMapper.apply(updateResult.getKeys())); }else{ runInsertReturning = sqlConnection -> sqlConnection .rxQueryWithParams(sql, bindValues) .map(queryResult -> keyMapper.apply(queryResult.getResults().get(0))); } return getConnection().flatMap(executeAndClose(runInsertReturning)); }
Example #15
Source File: TransactionRepository.java From trust-wallet-android-source with GNU General Public License v3.0 | 6 votes |
@Override public Single<String> createTransaction(Wallet from, String toAddress, BigInteger subunitAmount, BigInteger gasPrice, BigInteger gasLimit, byte[] data, String password) { final Web3j web3j = Web3jFactory.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl)); return Single.fromCallable(() -> { EthGetTransactionCount ethGetTransactionCount = web3j .ethGetTransactionCount(from.address, DefaultBlockParameterName.LATEST) .send(); return ethGetTransactionCount.getTransactionCount(); }) .flatMap(nonce -> accountKeystoreService.signTransaction(from, password, toAddress, subunitAmount, gasPrice, gasLimit, nonce.longValue(), data, networkRepository.getDefaultNetwork().chainId)) .flatMap(signedMessage -> Single.fromCallable( () -> { EthSendTransaction raw = web3j .ethSendRawTransaction(Numeric.toHexString(signedMessage)) .send(); if (raw.hasError()) { throw new ServiceException(raw.getError().getMessage()); } return raw.getTransactionHash(); })).subscribeOn(Schedulers.io()); }
Example #16
Source File: PermissionTicketServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_successMultipleResources() { //Prepare request List<PermissionRequest> request = Arrays.asList( new PermissionRequest().setResourceId("one").setResourceScopes(Arrays.asList("a","b")), new PermissionRequest().setResourceId("two").setResourceScopes(Arrays.asList("c","d")) ); // Prepare Resource List<Resource> found = request.stream() .map(s -> new Resource().setId(s.getResourceId()).setResourceScopes(s.getResourceScopes())) .collect(Collectors.toList()); when(resourceService.findByDomainAndClientAndResources(DOMAIN_ID, CLIENT_ID, Arrays.asList("one","two"))).thenReturn(Single.just(found)); when(repository.create(any())).thenReturn(Single.just(new PermissionTicket().setId("success"))); TestObserver<PermissionTicket> testObserver = service.create(request, DOMAIN_ID, CLIENT_ID).test(); testObserver.assertNoErrors().assertComplete().assertValue(permissionTicket -> "success".equals(permissionTicket.getId())); verify(repository, times(1)).create(any()); }
Example #17
Source File: ApiResource.java From redpipe with Apache License 2.0 | 6 votes |
@RequiresPermissions("update") @PUT @Path("pages/{id}") public Single<Response> apiUpdatePage(@PathParam("id") String id, @ApiUpdateValid("markdown") JsonObject page, @Context HttpServerRequest req, @Context Vertx vertx){ return Fibers.fiber(() -> { Optional<Pages> res = Fibers.await(dao.findOneById(Integer.valueOf(id))); if(!res.isPresent()) return Response.status(Status.NOT_FOUND).build(); Fibers.await(dao.update(res.get().setContent(page.getString("markdown")))); JsonObject event = new JsonObject() .put("id", id) .put("client", page.getString("client")); vertx.eventBus().publish("page.saved", event); return Response.ok(new JsonObject().put("success", true)).build(); }); }
Example #18
Source File: DeletionConverter.java From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override Single<? extends SMSSubmission> convert(@NonNull String uid, String user, int submissionId) { return Single.fromCallable(() -> { DeleteSMSSubmission subm = new DeleteSMSSubmission(); subm.setSubmissionID(submissionId); subm.setUserID(user); subm.setEvent(uid); return subm; }); }
Example #19
Source File: LocalMusicSource.java From Melophile with Apache License 2.0 | 5 votes |
@Override public Single<List<Track>> getTracksBy(MelophileTheme theme) { if (theme != null) { return Single.fromCallable(() -> trackHandler.queryByTheme(theme)); } return Single.error(new IllegalArgumentException("Theme is null")); }
Example #20
Source File: KeystoreAccountService.java From alpha-wallet-android with MIT License | 5 votes |
/** * Import private key to keystore * * @param privateKey * @param newPassword * @return */ @Override public Single<Wallet> importPrivateKey(String privateKey, String newPassword) { return Single.fromCallable(() -> { BigInteger key = new BigInteger(privateKey, PRIVATE_KEY_RADIX); ECKeyPair keypair = ECKeyPair.create(key); WalletFile wFile = org.web3j.crypto.Wallet.createLight(newPassword, keypair); return objectMapper.writeValueAsString(wFile); }).compose(upstream -> importKeystore(upstream.blockingGet(), newPassword, newPassword)); }
Example #21
Source File: UserAuthenticateCallFactory.java From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License | 5 votes |
public Single<User> logIn(final String username, final String password, final String serverUrl) { return Single.create(emitter -> { try { emitter.onSuccess(loginInternal(username, password, serverUrl)); } catch (Throwable t) { emitter.onError(t); } }); }
Example #22
Source File: GrpcBurstNodeService.java From burstkit4j with Apache License 2.0 | 5 votes |
@Override public Single<AT[]> getAccountATs(BurstAddress accountId) { return assign(() -> brsGrpc.getAccountATs(getAccountRequestFromId(accountId))) .map(accountATs -> accountATs.getAtsList() .stream() .map(AT::new) .toArray(AT[]::new)); }
Example #23
Source File: TrueTimeRx.java From truetime-android with Apache License 2.0 | 5 votes |
/** * Initialize TrueTime * See {@link #initializeNtp(String)} for details on working * * @return accurate NTP Date */ public Single<Date> initializeRx(String ntpPoolAddress) { return isInitialized() ? Single.just(now()) : initializeNtp(ntpPoolAddress).map(new Function<long[], Date>() { @Override public Date apply(long[] longs) throws Exception { return now(); } }); }
Example #24
Source File: AuthController.java From kyoko with MIT License | 5 votes |
@Get("/oauth2exchange") Single<HttpResponse> oauth2exchange(@Nullable String code, @Nullable Boolean bot) { var scope = "identify guilds" + (bot != null && bot ? " bot" : ""); return sessionManager.exchangeCode(code, Settings.instance().apiUrls().get("redirect"), scope) .switchIfEmpty(Maybe.error(new NoSuchElementException("no element returned"))) .doOnError(err -> logger.error("Error while exchanging OAuth2 code!", err)) .flatMapSingle(session -> Single.<HttpResponse>just(HttpResponse.ok(new OAuth2ExchangeResponse(session.getToken())))) .onErrorReturnItem(ErrorResponse.get(ErrorCode.INVALID_OAUTH2_CODE)); }
Example #25
Source File: ResourceServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void update_scopeNotFound() { NewResource newResource = new JsonObject("{\"resource_scopes\":[\"scope\"]}").mapTo(NewResource.class); Resource exitingRS = new Resource().setId(RESOURCE_ID).setDomain(DOMAIN_ID); when(scopeService.findByDomainAndKeys(DOMAIN_ID, Arrays.asList("scope"))).thenReturn(Single.just(Collections.emptyList())); when(repository.findByDomainAndClientAndUserAndResource(DOMAIN_ID, CLIENT_ID, USER_ID, RESOURCE_ID)).thenReturn(Maybe.just(exitingRS)); TestObserver<Resource> testObserver = service.update(newResource, DOMAIN_ID, CLIENT_ID, USER_ID, RESOURCE_ID).test(); testObserver.assertError(ScopeNotFoundException.class); verify(repository, times(0)).update(any()); }
Example #26
Source File: OnErrorCrash.java From akarnokd-misc with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { Single.fromCallable(() -> { throw new RuntimeException(); }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.computation()) .subscribe(v -> { }, e -> { throw new RuntimeException(e); }); Thread.sleep(50000); }
Example #27
Source File: IntegrationTestBase.java From vertx-elasticsearch-service with Apache License 2.0 | 5 votes |
@Test public void testDeleteRx2(TestContext testContext) throws Exception { final Async async = testContext.async(2); final JsonObject source = new JsonObject() .put("user", source_user) .put("message", source_message) .put("obj", new JsonObject() .put("array", new JsonArray() .add("1") .add("2"))); final UUID documentId = UUID.randomUUID(); final IndexOptions indexOptions = new IndexOptions().setId(documentId.toString()); rx2Service.index(index, type, source, indexOptions) .flatMap(indexResponse -> { return Single.create(emitter -> { vertx.setTimer(2000l, event -> { emitter.onSuccess(indexResponse); }); }); }) .flatMap(indexResponse -> rx2Service.delete(index, type, documentId.toString(), new DeleteOptions().setRefresh(RefreshPolicy.IMMEDIATE))) .subscribe( deleteResponse -> { assertDelete(testContext, deleteResponse, documentId); async.complete(); }, error -> testContext.fail(error) ); }
Example #28
Source File: UniConvertToTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testCreatingASingleFromNull() { Single<Optional<Integer>> single = Uni.createFrom().item((Integer) null).convert() .with(UniRxConverters.toSingle()); assertThat(single).isNotNull(); single .test() .assertValue(Optional.empty()) .assertComplete(); }
Example #29
Source File: PreparedDeleteCollectionOfObjectsTest.java From storio with Apache License 2.0 | 5 votes |
@Test public void shouldDeleteObjectsWithTypeMappingAsSingle() { final DeleteObjectsStub deleteStub = DeleteObjectsStub.newInstanceForDeleteMultipleObjectsWithTypeMapping(); final Single<DeleteResults<TestItem>> single = deleteStub.storIOContentResolver .delete() .objects(deleteStub.items) .prepare() .asRxSingle(); deleteStub.verifyBehaviorForDeleteMultipleObjects(single); }
Example #30
Source File: ThreadsListFragmentPresenter.java From demo-firebase-android with The Unlicense | 5 votes |
private Single<List<String>> getUserChannels(String username) { return Single.create(emitter -> { firebaseFirestore.collection(COLLECTION_USERS) .document(username) .get() .addOnCompleteListener(task -> { if (task.isSuccessful()) { emitter.onSuccess((List<String>) task.getResult().get(KEY_PROPERTY_CHANNELS)); } else { emitter.onError(task.getException()); } }); }); }