/** * Generates a {@link Completable} from {@link SQLConnection} operations. * * @param client the {@link SQLClient} * @param sourceSupplier a user-provided function returning a {@link Completable} generated by interacting with the given {@link SQLConnection} * @return a {@link Completable} generated from {@link SQLConnection} operations */ public static Completable usingConnectionCompletable(SQLClient client, Function<SQLConnection, Completable> sourceSupplier) { return client.rxGetConnection().flatMapCompletable(conn -> { return sourceSupplier.apply(conn).doAfterTerminate(conn::close); }); }
/** * Generates a {@link Completable} from {@link SQLConnection} operations. * * @param client the {@link SQLClient} * @param sourceSupplier a user-provided function returning a {@link Completable} generated by interacting with the given {@link SQLConnection} * @return a {@link Completable} generated from {@link SQLConnection} operations */ public static Completable usingConnectionCompletable(SQLClient client, Function<SQLConnection, Completable> sourceSupplier) { return client.rxGetConnection().flatMapCompletable(conn -> { return sourceSupplier.apply(conn).doAfterTerminate(conn::close); }); }
@Override public Completable init(XMLChunkMeta meta) { return canMerge(meta) .flatMapCompletable(b -> { if (b) { return mergeParents(meta); } return Completable.error(new IllegalArgumentException( "Chunk cannot be merged with this strategy")); }); }
/** * Append tags * @param search the search query * @param path the path * @param tags the tags to append * @return a Completable that completes when the tags have been appended */ private Completable appendTags(String search, String path, String tags) { return Single.just(tags) .map(x -> x.split(",")) .map(Arrays::asList) .flatMapCompletable(tagList -> store.rxAppendTags(search, path, tagList)); }
@Override public Completable merge(ChunkReadStream chunk, XMLChunkMeta meta, WriteStream<Buffer> out) { return canMerge(meta) .flatMapCompletable(b -> { if (!b) { return Completable.error(new IllegalStateException( "Chunk cannot be merged with this strategy")); } if (!headerWritten) { writeHeader(out); headerWritten = true; } return writeChunk(chunk, meta, out); }); }
/** * Update a document using a painless script * @param postFilter the filter to select the documents * @param updateScript the script which should be applied to the documents * @return a Completable that completes if the update is successful or fails * if an error occurs */ private Completable updateDocuments(JsonObject postFilter, JsonObject updateScript) { return client.updateByQuery(TYPE_NAME, postFilter, updateScript) .flatMapCompletable(sr -> { if (sr.getBoolean("timed_out", true)) { return Completable.error(new TimeoutException()); } return Completable.complete(); }); } }
private void startRefreshLocationTimerAsync(boolean initialization) { if (this.isClosed) { logger.info("startRefreshLocationTimerAsync: nothing to do, it is closed"); return; } logger.debug("registering a refresh in [{}] ms", this.backgroundRefreshLocationTimeIntervalInMS); LocalDateTime now = LocalDateTime.now(); int delayInMillis = initialization ? 0: this.backgroundRefreshLocationTimeIntervalInMS; Observable.timer(delayInMillis, TimeUnit.MILLISECONDS) .toSingle().flatMapCompletable( t -> { if (this.isClosed) { logger.warn("client already closed"); return Completable.error(new IllegalStateException("Client already closed")); } logger.debug("startRefreshLocationTimerAsync() - Invoking refresh, I was registered on [{}]", now); Single<DatabaseAccount> databaseAccountObs = GlobalEndpointManager.getDatabaseAccountFromAnyLocationsAsync(this.defaultEndpoint, new ArrayList<>(this.connectionPolicy.getPreferredLocations()), url -> this.getDatabaseAccountAsync(url)).toObservable().toSingle(); return databaseAccountObs.flatMapCompletable(dbAccount -> { logger.debug("db account retrieved"); return this.refreshLocationPrivateAsync(dbAccount); }); }).onErrorResumeNext(ex -> { logger.error("startRefreshLocationTimerAsync() - Unable to refresh database account from any location. Exception: {}", ex.toString(), ex); this.startRefreshLocationTimerAsync(); return Completable.complete(); }).toObservable().subscribeOn(scheduler).toBlocking().toFuture(); }
/** * Ensure the Elasticsearch mapping exists * @param type the target type for the mapping * @return an observable that will emit a single item when the mapping has * been created or if it already exists */ @Override public Completable ensureMapping(String type, JsonObject mapping) { // check if the target type exists return typeExists(type).flatMapCompletable(exists -> { if (exists) { return Completable.complete(); } else { // target type does not exist. create the mapping. return putMapping(type, mapping).flatMapCompletable(ack -> { if (ack) { return Completable.complete(); } return Completable.error(new NoStackTraceThrowable("Mapping creation " + "was not acknowledged by Elasticsearch")); }); } }); }
/** * Ensure the Elasticsearch index exists * @return an observable that will emit a single item when the index has * been created or if it already exists */ @Override public Completable ensureIndex() { // check if the index exists return indexExists().flatMapCompletable(exists -> { if (exists) { return Completable.complete(); } else { // index does not exist. create it. return createIndex().flatMapCompletable(ack -> { if (ack) { return Completable.complete(); } return Completable.error(new NoStackTraceThrowable("Index creation " + "was not acknowledged by Elasticsearch")); }); } }); }
@Override public Completable send(Event event) { AnalyticsEventRequestBody body = new AnalyticsEventRequestBody(event.getData(), dateFormat.format(new Date(event.getTimeStamp()))); return analyticsBodyInterceptor.intercept(body) .flatMapCompletable(analyticsBody -> serviceV7.sendEvent(event.getEventName(), event.getAction() .name(), event.getContext(), (AnalyticsEventRequestBody) analyticsBody) .onErrorResumeNext(throwable -> { if (throwable instanceof IllegalStateException) { return Observable.error(throwable); } return Observable.empty(); }) .toCompletable()); }
.flatMapCompletable(success -> { if (success) {
this.locationCache.onDatabaseAccountRead(dbAccount); return dbAccount; }).flatMapCompletable(dbAccount -> {
@Override public Completable init(XMLChunkMeta meta) { if (mergeStarted) { return Completable.error(new IllegalStateException("You cannot " + "initialize the merger anymore after merging has begun")); } if (strategy == null) { strategy = nextStrategy(); } return strategy.canMerge(meta) .flatMapCompletable(canMerge -> { if (canMerge) { // current strategy is able to handle the chunk return strategy.init(meta); } // current strategy cannot merge the chunk. select next one and retry. MergeStrategy ns = nextStrategy(); if (ns == null) { return Completable.error(new UnsupportedOperationException( "Cannot merge chunks. No valid strategy available.")); } ns.setParents(strategy.getParents()); strategy = ns; return init(meta); }); }
/** * Set properties * @param search the search query * @param path the path * @param properties the properties to set * @return a Completable that completes when the properties have been set */ private Completable setProperties(String search, String path, String properties) { return Single.just(properties) .map(x -> x.split(",")) .map(Arrays::asList) .flatMap(x -> { try { return Single.just(parseProperties(x)); } catch (ServerAPIException e) { return Single.error(e); } }) .flatMapCompletable(map -> store.rxSetProperties(search, path, map)); }
protected Completable rxAssertAutoCommit(SQLConnection conn) { String testName = UUID.randomUUID().toString(); return conn.rxExecute(String.format(INSERT_FOLK_SQL, testName)).toCompletable() .andThen(client.rxGetConnection().flatMapCompletable(other -> { return uniqueNames(other).contains(testName).toSingle() .flatMapCompletable(contains -> { if (contains) { return Completable.complete(); } return Completable.error(new AssertionError("Connection should be back in autocommit mode")); }) .doAfterTerminate(other::close); })); }
@Override public void start(Future<Void> startFuture) { // load and copy all indexer factories now and not lazily to avoid // concurrent modifications to the service loader's internal cache indexerFactories = ImmutableList.copyOf(FilteredServiceLoader.load(IndexerFactory.class)); queryCompiler = createQueryCompiler(); queryCompiler.setQueryCompilers(indexerFactories); new ElasticsearchClientFactory(vertx).createElasticsearchClient(INDEX_NAME) .doOnSuccess(es -> { client = es; }) .flatMapCompletable(v -> client.ensureIndex()) .andThen(Completable.defer(() -> ensureMapping())) .subscribe(() -> { registerMessageConsumers(); startFuture.complete(); }, startFuture::fail); }
client = es; }) .flatMapCompletable(v -> client.ensureIndex()) .andThen(Completable.defer(this::ensureMapping)) .subscribe(() -> {
private Completable inTransaction(Exception e) throws Exception { return client.rxGetConnection().flatMapCompletable(conn -> { return rxInsertExtraFolks(conn) .andThen(uniqueNames(conn)) .<List<String>>collect(ArrayList::new, List::add).toSingle() .flatMapCompletable(names -> rxAssertEquals(Arrays.asList(namesWithExtraFolks()), names)) .compose(upstream -> e == null ? upstream : upstream.andThen(Completable.error(e))) .compose(SQLClientHelper.txCompletableTransformer(conn)) .andThen(rxAssertAutoCommit(conn)) .doAfterTerminate(conn::close); }); } }
@Override public void setUp() throws Exception { super.setUp(); client = new JDBCClient(io.vertx.ext.jdbc.JDBCClient.createNonShared(vertx, config)); client.rxGetConnection().flatMapCompletable(conn -> { Completable setup = conn.rxExecute("drop table folks if exists").toCompletable() .andThen(conn.rxExecute("create table folks (firstname varchar(255) not null)").toCompletable()); for (String name : NAMES) { setup = setup.andThen(conn.rxExecute(String.format(INSERT_FOLK_SQL, name)).toCompletable()); } return setup.doAfterTerminate(conn::close); }).await(); }
/** * Test if canMerge works correctly * @param context the test context */ @Test public void canMerge(TestContext context) { XMLChunkMeta cm2 = new XMLChunkMeta(Arrays.asList(new XMLStartElement("other")), 10, 20); XMLChunkMeta cm3 = new XMLChunkMeta(Arrays.asList(new XMLStartElement("pre", "root")), 10, 20); XMLChunkMeta cm4 = new XMLChunkMeta(Arrays.asList(new XMLStartElement(null, "root", new String[] { "" }, new String[] { "uri" })), 10, 20); Async async = context.async(); MergeStrategy strategy = new AllSameStrategy(); strategy.canMerge(cm) .doOnSuccess(context::assertTrue) .flatMapCompletable(v -> strategy.init(cm)) .andThen(strategy.canMerge(cm)) .doOnSuccess(context::assertTrue) .flatMap(v -> strategy.canMerge(cm2)) .doOnSuccess(context::assertFalse) .flatMap(v -> strategy.canMerge(cm3)) .doOnSuccess(context::assertFalse) .flatMap(v -> strategy.canMerge(cm4)) .doOnSuccess(context::assertFalse) .subscribe(v -> { async.complete(); }, context::fail); }