本文整理汇总了Java中org.apache.curator.framework.api.BackgroundCallback类的典型用法代码示例。如果您正苦于以下问题:Java BackgroundCallback类的具体用法?Java BackgroundCallback怎么用?Java BackgroundCallback使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
BackgroundCallback类属于org.apache.curator.framework.api包,在下文中一共展示了BackgroundCallback类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: purge
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
/**
*
* trigger a purge operation
* @param path pathn
* @param id yarn ID
* @param policyMatch policy to match ID on
* @param purgePolicy policy when there are children under a match
* @param callback optional callback
* @return the number purged
* @throws IOException
*/
public int purge(String path,
String id,
String policyMatch,
RegistryAdminService.PurgePolicy purgePolicy,
BackgroundCallback callback) throws
IOException,
ExecutionException,
InterruptedException {
Future<Integer> future = registry.purgeRecordsAsync(path,
id, policyMatch, purgePolicy, callback);
try {
return future.get();
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw e;
}
}
}
示例2: existsThrows
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
private <T extends SingularityId> List<T> existsThrows(final String pathNameforLogs, final Collection<String> paths, final IdTranscoder<T> idTranscoder) throws Exception {
if (paths.isEmpty()) {
return Collections.emptyList();
}
final List<T> objects = Lists.newArrayListWithCapacity(paths.size());
final CountDownLatch latch = new CountDownLatch(paths.size());
final BackgroundCallback callback = new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
try {
if (event.getStat() != null) {
objects.add(Transcoders.getFromStringFunction(idTranscoder).apply(ZKPaths.getNodeFromPath(event.getPath())));
}
} finally {
latch.countDown();
}
}
};
return queryAndReturnResultsThrows(objects, paths, callback, latch, pathNameforLogs, new AtomicInteger(), CuratorQueryMethod.GET_DATA);
}
示例3: notExistsThrows
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
private <T extends SingularityId> List<T> notExistsThrows(final String pathNameforLogs, final Map<String, T> pathsMap) throws Exception {
if (pathsMap.isEmpty()) {
return Collections.emptyList();
}
final List<T> objects = Lists.newArrayListWithCapacity(pathsMap.size());
final CountDownLatch latch = new CountDownLatch(pathsMap.size());
final BackgroundCallback callback = new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
try {
if (event.getStat() == null) {
objects.add(pathsMap.get(event.getPath()));
}
} finally {
latch.countDown();
}
}
};
return queryAndReturnResultsThrows(objects, pathsMap.keySet(), callback, latch, pathNameforLogs, new AtomicInteger(), CuratorQueryMethod.CHECK_EXISTS);
}
示例4: queryAndReturnResultsThrows
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
private <T> T queryAndReturnResultsThrows(final T results, final Collection<String> paths, final BackgroundCallback callback, final CountDownLatch latch, final String pathNameForLogs, final AtomicInteger bytes, final CuratorQueryMethod method) throws Exception {
final long start = System.currentTimeMillis();
try {
for (String path : paths) {
switch (method) {
case GET_DATA:
curator.getData().inBackground(callback).forPath(path);
break;
case GET_CHILDREN:
curator.getChildren().inBackground(callback).forPath(path);
break;
case CHECK_EXISTS:
default:
curator.checkExists().inBackground(callback).forPath(path);
break;
}
}
checkLatch(latch, pathNameForLogs);
} finally {
log(OperationType.READ, Optional.of(paths.size()), bytes.get() > 0 ? Optional.of(bytes.get()) : Optional.<Integer>absent(), start, pathNameForLogs);
}
return results;
}
示例5: callback
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
private BackgroundCallback callback(Consumer<CuratorEvent> result, Consumer<Throwable> exception, String path) {
return (client, event) -> {
if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
result.accept(event);
} else if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() ||
event.getResultCode() == KeeperException.Code.SESSIONEXPIRED.intValue() ||
event.getResultCode() == KeeperException.Code.SESSIONMOVED.intValue() ||
event.getResultCode() == KeeperException.Code.OPERATIONTIMEOUT.intValue()) {
exception.accept(StoreException.create(StoreException.Type.CONNECTION_ERROR, path));
} else if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
exception.accept(StoreException.create(StoreException.Type.DATA_EXISTS, path));
} else if (event.getResultCode() == KeeperException.Code.BADVERSION.intValue()) {
exception.accept(StoreException.create(StoreException.Type.WRITE_CONFLICT, path));
} else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
exception.accept(StoreException.create(StoreException.Type.DATA_NOT_FOUND, path));
} else if (event.getResultCode() == KeeperException.Code.NOTEMPTY.intValue()) {
exception.accept(StoreException.create(StoreException.Type.DATA_CONTAINS_ELEMENTS, path));
} else {
exception.accept(StoreException.create(StoreException.Type.UNKNOWN,
KeeperException.create(KeeperException.Code.get(event.getResultCode()), path)));
}
};
}
示例6: createNode
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
private CompletableFuture<Void> createNode(CreateMode createMode, boolean createParents, String path, byte[] data) {
CompletableFuture<Void> result = new CompletableFuture<>();
try {
BackgroundCallback callback = (cli, event) -> {
if (event.getResultCode() == KeeperException.Code.OK.intValue() ||
event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
result.complete(null);
} else {
result.completeExceptionally(translateErrorCode(path, event));
}
};
if (createParents) {
client.create().creatingParentsIfNeeded().withMode(createMode).inBackground(callback, executor)
.forPath(path, data);
} else {
client.create().withMode(createMode).inBackground(callback, executor).forPath(path, data);
}
} catch (Exception e) {
result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e));
}
return result;
}
示例7: releaseAndTryRemove
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
/**
* Releases the lock for the given state node and tries to remove the state node if it is no longer locked.
* The deletion of the state node is executed asynchronously. After the state node has been deleted, the given
* callback is called with the {@link RetrievableStateHandle} of the deleted state node.
*
* <p><strong>Important</strong>: This also discards the stored state handle after the given action
* has been executed.
*
* @param pathInZooKeeper Path of state handle to remove
* @param callback The callback to execute after a successful deletion. Null if no action needs to be executed.
* @throws Exception If the ZooKeeper operation fails
*/
public void releaseAndTryRemove(
String pathInZooKeeper,
@Nullable final RemoveCallback<T> callback) throws Exception {
checkNotNull(pathInZooKeeper, "Path in ZooKeeper");
final String path = normalizePath(pathInZooKeeper);
RetrievableStateHandle<T> stateHandle = null;
try {
stateHandle = get(path, false);
} catch (Exception e) {
LOG.warn("Could not retrieve the state handle from node " + path + '.', e);
}
release(pathInZooKeeper);
final BackgroundCallback backgroundCallback = new RemoveBackgroundCallback<>(stateHandle, callback, path);
client.delete().inBackground(backgroundCallback, executor).forPath(path);
}
示例8: createEphemeralNodeRecursionInBackground
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
public void createEphemeralNodeRecursionInBackground(String path) throws Exception {
curatorFramework.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
LOG.info("event's result code: {}, type: {}", event.getResultCode(), event.getType());
showCurrentThreadName();
countDownLatch.countDown();
}
}).forPath(path);
}
示例9: queryAndReturnResultsThrows
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
private <T> T queryAndReturnResultsThrows(final T results, final Collection<String> paths, final BackgroundCallback callback, final CountDownLatch latch, final String pathNameForLogs, final AtomicInteger bytes, final CuratorQueryMethod method) throws Exception {
final long start = System.currentTimeMillis();
try {
for (String path : paths) {
switch (method) {
case GET_DATA:
curator.getData().inBackground(callback).forPath(path);
break;
case GET_CHILDREN:
curator.getChildren().inBackground(callback).forPath(path);
break;
case CHECK_EXISTS:
default:
curator.checkExists().inBackground(callback).forPath(path);
break;
}
}
checkLatch(latch, pathNameForLogs);
} finally {
log(method.operationType, Optional.of(paths.size()), bytes.get() > 0 ? Optional.of(bytes.get()) : Optional.<Integer>absent(), start, pathNameForLogs);
}
return results;
}
示例10: AsyncPurge
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
public AsyncPurge(String path,
NodeSelector selector,
PurgePolicy purgePolicy,
BackgroundCallback callback) {
this.callback = callback;
this.selector = selector;
this.path = path;
this.purgePolicy = purgePolicy;
}
示例11: getChildrenAsIdsForParentsThrows
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
private <T extends SingularityId> List<T> getChildrenAsIdsForParentsThrows(final String pathNameforLogs, final Collection<String> parents, final IdTranscoder<T> idTranscoder) throws Exception {
if (parents.isEmpty()) {
return Collections.emptyList();
}
final List<T> objects = Lists.newArrayListWithExpectedSize(parents.size());
final List<T> synchronizedObjects = Collections.synchronizedList(objects);
final CountDownLatch latch = new CountDownLatch(parents.size());
final BackgroundCallback callback = new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
try {
if (event.getChildren() == null || event.getChildren().size() == 0) {
LOG.trace("Expected children for node {} - but found none", event.getPath());
return;
}
synchronizedObjects.addAll(Lists.transform(event.getChildren(), Transcoders.getFromStringFunction(idTranscoder)));
} finally {
latch.countDown();
}
}
};
return queryAndReturnResultsThrows(synchronizedObjects, parents, callback, latch, pathNameforLogs, new AtomicInteger(), CuratorQueryMethod.GET_CHILDREN);
}
示例12: getAsyncNestedChildDataAsMapThrows
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
protected <T, Q> Map<T, List<Q>> getAsyncNestedChildDataAsMapThrows(final String pathNameForLogs, final Map<String, T> parentPathsMap, final String subpath, final Transcoder<Q> transcoder) throws Exception {
final Map<String, T> allPathsMap = Maps.newHashMap();
for (Map.Entry<String, T> entry : parentPathsMap.entrySet()) {
for (String child : getChildren(ZKPaths.makePath(entry.getKey(), subpath))) {
allPathsMap.put(ZKPaths.makePath(entry.getKey(), subpath, child), entry.getValue());
}
}
final ConcurrentHashMap<T, List<Q>> resultsMap = new ConcurrentHashMap<>();
final CountDownLatch latch = new CountDownLatch(allPathsMap.size());
final AtomicInteger bytes = new AtomicInteger();
final BackgroundCallback callback = new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
try {
if (event.getData() == null || event.getData().length == 0) {
LOG.trace("Expected active node {} but it wasn't there", event.getPath());
return;
}
bytes.getAndAdd(event.getData().length);
final Q object = transcoder.fromBytes(event.getData());
if (allPathsMap.get(event.getPath()) != null) {
resultsMap.putIfAbsent(allPathsMap.get(event.getPath()), new ArrayList<Q>());
resultsMap.get(allPathsMap.get(event.getPath())).add(object);
}
} finally {
latch.countDown();
}
}
};
return queryAndReturnResultsThrows(resultsMap, allPathsMap.keySet(), callback, latch, pathNameForLogs, bytes, CuratorQueryMethod.GET_DATA);
}
示例13: testDelete
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
public void testDelete() throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181,localhost:3181,localhost:4181", new ExponentialBackoffRetry(1000, 4));
client.start();
client.delete().inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
System.out.println(JsonHelper.toJson(curatorEvent));
}
}).forPath("/curd-test/delete");
Thread.sleep(10000);
}
示例14: testRemoveWithCallback
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
/**
* Tests that state handles are correctly removed with a callback.
*/
@Test
public void testRemoveWithCallback() throws Exception {
// Setup
LongStateStorage stateHandleProvider = new LongStateStorage();
ZooKeeperStateHandleStore<Long> store = new ZooKeeperStateHandleStore<>(
ZooKeeper.getClient(), stateHandleProvider, Executors.directExecutor());
// Config
final String pathInZooKeeper = "/testRemoveWithCallback";
final Long state = 27255442L;
store.add(pathInZooKeeper, state);
final CountDownLatch sync = new CountDownLatch(1);
BackgroundCallback callback = mock(BackgroundCallback.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
sync.countDown();
return null;
}
}).when(callback).processResult(eq(ZooKeeper.getClient()), any(CuratorEvent.class));
// Test
store.remove(pathInZooKeeper, callback);
// Verify discarded and callback called
assertEquals(0, ZooKeeper.getClient().getChildren().forPath("/").size());
sync.await();
verify(callback, times(1))
.processResult(eq(ZooKeeper.getClient()), any(CuratorEvent.class));
}
示例15: getNodeData
import org.apache.curator.framework.api.BackgroundCallback; //导入依赖的package包/类
@Override
protected <M extends Message> ListenableFuture<M> getNodeData(
WatchCallback watcher,
String path,
final Message.Builder builder) {
final SettableFuture<M> future = SettableFuture.create();
Watcher wc = ZkWatcherCallback.makeZkWatcher(watcher);
BackgroundCallback cb = new BackgroundCallback() {
@Override
@SuppressWarnings("unchecked") // we don't know what M is until runtime
public void processResult(CuratorFramework aClient, CuratorEvent event) throws Exception {
byte[] data;
if (event != null & (data = event.getData()) != null) {
builder.mergeFrom(data);
safeSetFuture(future, (M) builder.build());
} else {
safeSetException(future, new RuntimeException("Failed to fetch data from path: "
+ event.getPath()));
}
}
};
try {
client.getData().usingWatcher(wc).inBackground(cb).forPath(path);
// Suppress it since forPath() throws Exception
// SUPPRESS CHECKSTYLE IllegalCatch
} catch (Exception e) {
safeSetException(future, new RuntimeException("Could not getNodeData", e));
}
return future;
}