Example usage for org.apache.zookeeper KeeperException code

List of usage examples for org.apache.zookeeper KeeperException code

Introduction

In this page you can find the example usage for org.apache.zookeeper KeeperException code.

Prototype

Code code

To view the source code for org.apache.zookeeper KeeperException code.

Click Source Link

Usage

From source file:com.twitter.distributedlog.util.FutureUtils.java

License:Apache License

/**
 * Convert the <i>throwable</i> to zookeeper related exceptions.
 *
 * @param throwable cause/*from   w  ww.  j a  va2 s . c  o m*/
 * @param path zookeeper path
 * @return zookeeper related exceptions
 */
public static Throwable zkException(Throwable throwable, String path) {
    if (throwable instanceof KeeperException) {
        return throwable;
    } else if (throwable instanceof ZooKeeperClient.ZooKeeperConnectionException) {
        return KeeperException.create(KeeperException.Code.CONNECTIONLOSS, path);
    } else if (throwable instanceof InterruptedException) {
        return new DLInterruptedException("Interrupted on operating " + path, throwable);
    } else {
        return new UnexpectedException("Encountered unexpected exception on operatiing " + path, throwable);
    }
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Asynchronously create zookeeper path recursively and optimistically.
 *
 * @param zkc Zookeeper client//from   ww  w .  ja  va  2  s  . c o  m
 * @param pathToCreate  Zookeeper full path
 * @param parentPathShouldNotCreate The recursive creation should stop if this path doesn't exist
 * @param data Zookeeper data
 * @param acl Acl of the zk path
 * @param createMode Create mode of zk path
 * @param callback Callback
 * @param ctx Context object
 */
public static void zkAsyncCreateFullPathOptimisticRecursive(final ZooKeeperClient zkc,
        final String pathToCreate, final Optional<String> parentPathShouldNotCreate, final byte[] data,
        final List<ACL> acl, final CreateMode createMode, final AsyncCallback.StringCallback callback,
        final Object ctx) {
    try {
        zkc.get().create(pathToCreate, data, acl, createMode, new AsyncCallback.StringCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, String name) {

                if (rc != KeeperException.Code.NONODE.intValue()) {
                    callback.processResult(rc, path, ctx, name);
                    return;
                }

                // Since we got a nonode, it means that my parents may not exist
                // ephemeral nodes can't have children so Create mode is always
                // persistent parents
                int lastSlash = pathToCreate.lastIndexOf('/');
                if (lastSlash <= 0) {
                    callback.processResult(rc, path, ctx, name);
                    return;
                }
                String parent = pathToCreate.substring(0, lastSlash);
                if (parentPathShouldNotCreate.isPresent()
                        && Objects.equal(parentPathShouldNotCreate.get(), parent)) {
                    // we should stop here
                    callback.processResult(rc, path, ctx, name);
                    return;
                }
                zkAsyncCreateFullPathOptimisticRecursive(zkc, parent, parentPathShouldNotCreate, new byte[0],
                        acl, CreateMode.PERSISTENT, new AsyncCallback.StringCallback() {
                            @Override
                            public void processResult(int rc, String path, Object ctx, String name) {
                                if (rc == KeeperException.Code.OK.intValue()
                                        || rc == KeeperException.Code.NODEEXISTS.intValue()) {
                                    // succeeded in creating the parent, now create the original path
                                    zkAsyncCreateFullPathOptimisticRecursive(zkc, pathToCreate,
                                            parentPathShouldNotCreate, data, acl, createMode, callback, ctx);
                                } else {
                                    callback.processResult(rc, path, ctx, name);
                                }
                            }
                        }, ctx);
            }
        }, ctx);
    } catch (ZooKeeperClient.ZooKeeperConnectionException zkce) {
        callback.processResult(DistributedLogConstants.ZK_CONNECTION_EXCEPTION_RESULT_CODE, zkce.getMessage(),
                ctx, pathToCreate);
    } catch (InterruptedException ie) {
        callback.processResult(DistributedLogConstants.DL_INTERRUPTED_EXCEPTION_RESULT_CODE, ie.getMessage(),
                ctx, pathToCreate);
    }
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Asynchronously create zookeeper path recursively and optimistically.
 *
 * @param zkc Zookeeper client//from www.  j a  va  2  s.  c  o m
 * @param pathToCreate  Zookeeper full path
 * @param data Zookeeper data
 * @param acl Acl of the zk path
 * @param createMode Create mode of zk path
 */
public static Future<BoxedUnit> zkAsyncCreateFullPathOptimisticAndSetData(final ZooKeeperClient zkc,
        final String pathToCreate, final byte[] data, final List<ACL> acl, final CreateMode createMode) {
    final Promise<BoxedUnit> result = new Promise<BoxedUnit>();

    try {
        zkc.get().setData(pathToCreate, data, -1, new AsyncCallback.StatCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, Stat stat) {
                if (rc != KeeperException.Code.NONODE.intValue()) {
                    handleKeeperExceptionCode(rc, path, result);
                    return;
                }

                Optional<String> parentPathShouldNotCreate = Optional.absent();
                zkAsyncCreateFullPathOptimisticRecursive(zkc, pathToCreate, parentPathShouldNotCreate, data,
                        acl, createMode, new AsyncCallback.StringCallback() {
                            @Override
                            public void processResult(int rc, String path, Object ctx, String name) {
                                handleKeeperExceptionCode(rc, path, result);
                            }
                        }, result);
            }
        }, result);
    } catch (Exception exc) {
        result.setException(exc);
    }

    return result;
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

private static void handleKeeperExceptionCode(int rc, String pathOrMessage, Promise<BoxedUnit> result) {
    if (KeeperException.Code.OK.intValue() == rc) {
        result.setValue(BoxedUnit.UNIT);
    } else if (DistributedLogConstants.ZK_CONNECTION_EXCEPTION_RESULT_CODE == rc) {
        result.setException(new ZooKeeperClient.ZooKeeperConnectionException(pathOrMessage));
    } else if (DistributedLogConstants.DL_INTERRUPTED_EXCEPTION_RESULT_CODE == rc) {
        result.setException(new DLInterruptedException(pathOrMessage));
    } else {/*from   w w w. j a  v a  2 s . c  o m*/
        result.setException(KeeperException.create(KeeperException.Code.get(rc), pathOrMessage));
    }
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Retrieve data from zookeeper <code>path</code>.
 *
 * @param path/*  ww w.ja  va2  s . c o m*/
 *          zookeeper path to retrieve data
 * @param watch
 *          whether to watch the path
 * @return future representing the versioned value. null version or null value means path doesn't exist.
 */
public static Future<Versioned<byte[]>> zkGetData(ZooKeeper zk, String path, boolean watch) {
    final Promise<Versioned<byte[]>> promise = new Promise<Versioned<byte[]>>();
    zk.getData(path, watch, new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            if (KeeperException.Code.OK.intValue() == rc) {
                if (null == stat) {
                    promise.setValue(new Versioned<byte[]>(null, null));
                } else {
                    promise.setValue(new Versioned<byte[]>(data, new ZkVersion(stat.getVersion())));
                }
            } else if (KeeperException.Code.NONODE.intValue() == rc) {
                promise.setValue(new Versioned<byte[]>(null, null));
            } else {
                promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
            }
        }
    }, null);
    return promise;
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Set <code>data</code> to zookeeper <code>path</code>.
 *
 * @param zk/*from   w  w w . ja  v  a2  s  .c  o  m*/
 *          zookeeper client
 * @param path
 *          path to set data
 * @param data
 *          data to set
 * @param version
 *          version used to set data
 * @return future representing the version after this operation.
 */
public static Future<ZkVersion> zkSetData(ZooKeeper zk, String path, byte[] data, ZkVersion version) {
    final Promise<ZkVersion> promise = new Promise<ZkVersion>();
    zk.setData(path, data, version.getZnodeVersion(), new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.updateIfEmpty(new Return<ZkVersion>(new ZkVersion(stat.getVersion())));
                return;
            }
            promise.updateIfEmpty(new Throw<ZkVersion>(KeeperException.create(KeeperException.Code.get(rc))));
            return;
        }
    }, null);
    return promise;
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Delete the given <i>path</i> from zookeeper.
 *
 * @param zk/*from  w ww.  j  av a 2  s.  c o m*/
 *          zookeeper client
 * @param path
 *          path to delete
 * @param version
 *          version used to set data
 * @return future representing the version after this operation.
 */
public static Future<Void> zkDelete(ZooKeeper zk, String path, ZkVersion version) {
    final Promise<Void> promise = new Promise<Void>();
    zk.delete(path, version.getZnodeVersion(), new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.updateIfEmpty(new Return<Void>(null));
                return;
            }
            promise.updateIfEmpty(new Throw<Void>(KeeperException.create(KeeperException.Code.get(rc))));
            return;
        }
    }, null);
    return promise;
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Sync zookeeper client on given <i>path</i>.
 *
 * @param zkc/* w w  w  .  ja va 2 s  .  c  o  m*/
 *          zookeeper client
 * @param path
 *          path to sync
 * @return zookeeper client after sync
 * @throws IOException
 */
public static ZooKeeper sync(ZooKeeperClient zkc, String path) throws IOException {
    ZooKeeper zk;
    try {
        zk = zkc.get();
    } catch (InterruptedException e) {
        throw new DLInterruptedException("Interrupted on checking if log " + path + " exists", e);
    }
    final CountDownLatch syncLatch = new CountDownLatch(1);
    final AtomicInteger syncResult = new AtomicInteger(0);
    zk.sync(path, new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            syncResult.set(rc);
            syncLatch.countDown();
        }
    }, null);
    try {
        syncLatch.await();
    } catch (InterruptedException e) {
        throw new DLInterruptedException("Interrupted on syncing zookeeper connection", e);
    }
    if (KeeperException.Code.OK.intValue() != syncResult.get()) {
        throw new ZKException("Error syncing zookeeper connection ",
                KeeperException.Code.get(syncResult.get()));
    }
    return zk;
}

From source file:com.twitter.distributedlog.zk.TestZKTransaction.java

License:Apache License

@Test(timeout = 60000)
public void testProcessNullResults() throws Exception {
    ZooKeeperClient zkc = mock(ZooKeeperClient.class);
    ZKTransaction transaction = new ZKTransaction(zkc);
    int numOps = 3;
    final CountDownLatch commitLatch = new CountDownLatch(numOps);
    final CountDownLatch abortLatch = new CountDownLatch(numOps);
    for (int i = 0; i < numOps; i++) {
        transaction.addOp(new CountDownZKOp(commitLatch, abortLatch));
    }//from   w  w  w  .ja  v a 2  s  .  com
    transaction.processResult(KeeperException.Code.CONNECTIONLOSS.intValue(), "test-path", null, null);
    abortLatch.await();
    assertEquals(0, abortLatch.getCount());
    assertEquals(numOps, commitLatch.getCount());
}

From source file:com.twitter.distributedlog.zk.TestZKVersionedSetOp.java

License:Apache License

@Test(timeout = 60000)
public void testAbortNullOpResult() throws Exception {
    final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ZKVersionedSetOp versionedSetOp = new ZKVersionedSetOp(mock(Op.class),
            new Transaction.OpListener<Version>() {
                @Override/*from w ww . ja  va2 s  .  c om*/
                public void onCommit(Version r) {
                    // no-op
                }

                @Override
                public void onAbort(Throwable t) {
                    exception.set(t);
                    latch.countDown();
                }
            });
    KeeperException ke = KeeperException.create(KeeperException.Code.SESSIONEXPIRED);
    versionedSetOp.abortOpResult(ke, null);
    latch.await();
    assertTrue(ke == exception.get());
}