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:io.pravega.controller.store.index.ZKHostIndex.java

License:Apache License

private CompletableFuture<Void> createNode(CreateMode createMode, boolean createParents, String path,
        byte[] data) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {//from   w w  w  .  jav a 2s  .c  o m
        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;
}

From source file:io.pravega.controller.store.index.ZKHostIndex.java

License:Apache License

private CompletableFuture<byte[]> readNode(String path) {
    CompletableFuture<byte[]> result = new CompletableFuture<>();
    try {//w ww .  j  a v a 2 s  .c  om
        client.getData().inBackground((cli, event) -> {
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                result.complete(event.getData());
            } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
                log.debug("Node {} does not exist.", path);
                result.complete(null);
            } else {
                result.completeExceptionally(translateErrorCode(path, event));
            }
        }, executor).forPath(path);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e));
    }
    return result;
}

From source file:io.pravega.controller.store.index.ZKHostIndex.java

License:Apache License

private CompletableFuture<Void> deleteNode(String path) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {//  w  w  w  . j  a  v a  2 s. c om
        client.delete().inBackground((cli, event) -> {
            if (event.getResultCode() == KeeperException.Code.OK.intValue()
                    || event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
                result.complete(null);
            } else {
                result.completeExceptionally(translateErrorCode(path, event));
            }
        }, executor).forPath(path);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e));
    }
    return result;
}

From source file:io.pravega.controller.store.index.ZKHostIndex.java

License:Apache License

private CompletableFuture<List<String>> getChildren(String path) {
    CompletableFuture<List<String>> result = new CompletableFuture<>();
    try {/*from w w w.  j  a  v a2  s  .  c om*/
        client.getChildren().inBackground((cli, event) -> {
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                result.complete(event.getChildren());
            } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
                result.complete(Collections.emptyList());
            } else {
                result.completeExceptionally(translateErrorCode(path, event));
            }
        }, executor).forPath(path);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e));
    }
    return result;
}

From source file:io.pravega.controller.store.index.ZKHostIndex.java

License:Apache License

private StoreException translateErrorCode(String path, CuratorEvent event) {
    StoreException ex;/*from   w  w  w .ja  va2s . c  o m*/
    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()) {
        ex = StoreException.create(StoreException.Type.CONNECTION_ERROR, path);
    } else if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
        ex = StoreException.create(StoreException.Type.DATA_EXISTS, path);
    } else if (event.getResultCode() == KeeperException.Code.BADVERSION.intValue()) {
        ex = StoreException.create(StoreException.Type.WRITE_CONFLICT, path);
    } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
        ex = StoreException.create(StoreException.Type.DATA_NOT_FOUND, path);
    } else if (event.getResultCode() == KeeperException.Code.NOTEMPTY.intValue()) {
        ex = StoreException.create(StoreException.Type.DATA_CONTAINS_ELEMENTS, path);
    } else {
        ex = StoreException.create(StoreException.Type.UNKNOWN,
                KeeperException.create(KeeperException.Code.get(event.getResultCode()), path));
    }
    return ex;
}

From source file:io.pravega.controller.store.stream.ZKStoreHelper.java

License:Open Source License

BackgroundCallback callback(Consumer<CuratorEvent> result, Consumer<Throwable> exception) {
    return (client, event) -> {
        if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
            result.accept(event);/*from   w ww .  ja va 2s  . c  o  m*/
        } 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(new StoreConnectionException("" + event.getResultCode()));
        } else if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
            exception.accept(new DataExistsException(event.getPath()));
        } else if (event.getResultCode() == KeeperException.Code.BADVERSION.intValue()) {
            exception.accept(new WriteConflictException(event.getPath()));
        } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
            exception.accept(new DataNotFoundException(event.getPath()));
        } else if (event.getResultCode() == KeeperException.Code.NOTEMPTY.intValue()) {
            exception.accept(new DataExistsException(event.getPath()));
        } else {
            exception
                    .accept(new RuntimeException("Curator background task errorCode:" + event.getResultCode()));
        }
    };
}

From source file:io.reign.conf.ConfService.java

License:Apache License

/**
 * //from   w  ww . ja va2 s . co  m
 * @param relativePath
 */
public void removeConf(String clusterId, String relativeConfPath) {
    String path = getPathScheme().getAbsolutePath(PathType.CONF,
            getPathScheme().joinPaths(clusterId, relativeConfPath));

    try {
        getZkClient().delete(path, -1);

    } catch (KeeperException e) {
        if (e.code() != Code.NONODE) {
            logger.error("removeConf():  error trying to delete node:  " + e + ":  path=" + path, e);
        }
    } catch (Exception e) {
        logger.error("removeConf():  error trying to delete node:  " + e + ":  path=" + path, e);
    }
}

From source file:io.reign.conf.ConfService.java

License:Apache License

<T> T getConfValue(String absolutePath, DataSerializer<T> confSerializer) {

    throwExceptionIfInvalidConfPath(absolutePath);

    byte[] bytes = null;
    T result = null;//from   ww w . j a va 2 s.c  o m

    try {

        // not in cache, so load from ZK
        Stat stat = new Stat();
        bytes = getZkClient().getData(absolutePath, true, stat);

        result = bytes != null ? confSerializer.deserialize(bytes) : null;

    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            // set up watch on that node
            try {
                getZkClient().exists(absolutePath, true);
            } catch (Exception e1) {
                logger.error("getConfValue():  error trying to watch node:  " + e1 + ":  path=" + absolutePath,
                        e1);
            }

            logger.debug(
                    "getConfValue():  error trying to fetch node info:  {}:  node does not exist:  path={}",
                    e.getMessage(), absolutePath);
        } else {
            logger.error("getConfValue():  error trying to fetch node info:  " + e, e);
        }
    } catch (Exception e) {
        logger.error("getConfValue():  error trying to fetch node info:  " + e, e);
    }

    return result;
}

From source file:io.reign.conf.ConfService.java

License:Apache License

@Override
public ResponseMessage handleMessage(RequestMessage requestMessage) {
    ResponseMessage responseMessage = new SimpleResponseMessage();
    try {/*ww w . j a  v a2  s  .  c  om*/
        /** preprocess request **/
        String requestBody = (String) requestMessage.getBody();
        int newlineIndex = requestBody.indexOf("\n");
        String resourceLine = requestBody;
        String confBody = null;
        if (newlineIndex != -1) {
            resourceLine = requestBody.substring(0, newlineIndex);
            confBody = requestBody.substring(newlineIndex + 1);
        }

        // get meta
        ParsedRequestMessage parsedRequestMessage = new ParsedRequestMessage(requestMessage);
        String meta = parsedRequestMessage.getMeta();
        String resource = parsedRequestMessage.getResource();

        // get resource; strip beginning and ending slashes "/"
        if (resource.startsWith("/")) {
            resource = resource.substring(1);
        }
        if (resource.endsWith("/")) {
            resource = resource.substring(0, resource.length() - 1);
        }

        /** get response **/
        String[] tokens = getPathScheme().tokenizePath(resource);

        String clusterId = null;
        String relativePath = null;
        if (tokens.length == 1) {
            // list configurations in cluster
            clusterId = tokens[0];

        } else if (tokens.length > 1) {
            clusterId = tokens[0];

            String[] relativePathTokens = Arrays.<String>copyOfRange(tokens, 1, tokens.length);
            relativePath = getPathScheme().joinTokens(relativePathTokens);

        }

        if (logger.isDebugEnabled()) {
            logger.debug("clusterId={}; relativePath={}; meta={}",
                    new Object[] { clusterId, relativePath, meta });
        }

        /** decide what to do based on meta value **/
        if (meta == null) {
            // get conf or list conf(s) available
            if (clusterId != null && relativePath != null) {
                if (isValidConfPath(relativePath)) {
                    Object conf = getConf(clusterId, relativePath);
                    if (conf != null) {
                        responseMessage.setBody(conf);
                    }
                } else {
                    // list items available
                    String absolutePath = getPathScheme().getAbsolutePath(PathType.CONF,
                            getPathScheme().joinPaths(clusterId, relativePath));
                    List<String> childList = getZkClient().getChildren(absolutePath, false);
                    responseMessage.setBody(childList);
                }

            } else if (clusterId != null && relativePath == null) {
                // list configs in cluster
                String absolutePath = getPathScheme().getAbsolutePath(PathType.CONF, clusterId);
                List<String> childList = getZkClient().getChildren(absolutePath, false);
                responseMessage.setBody(childList);

            } else {
                // both clusterId and relativePath are null: just list available clusters
                String absolutePath = getPathScheme().getAbsolutePath(PathType.CONF);
                List<String> childList = getZkClient().getChildren(absolutePath, false);
                responseMessage.setBody(childList);
            }

        } else if ("update".equals(meta) || "put".equals(meta)) {
            // edit conf (add, remove, or update properties)
            Map conf;
            if ("put".equals(meta)) {
                logger.info("PUT configuration:  clusterId={}; path={}", clusterId, relativePath);

                conf = new HashMap<String, Object>();

            } else {
                logger.info("UPDATE configuration:  clusterId={}; path={}", clusterId, relativePath);

                conf = getConf(clusterId, relativePath);

                // set existing configuration in response now so even if we get unexpected error, it will show in
                // response
                responseMessage.setBody(conf);

                // create one to build upon if doesn't exist yet
                if (conf == null) {
                    // if this is a new configuration
                    conf = new HashMap<String, Object>();
                }
            }

            // TODO: use UTF-8 universally in the future?
            // read in api body as properties for easier processing
            Map<String, String> updateConf = new HashMap<String, String>();
            if (confBody != null) {
                String[] confBodyLines = confBody.split("\n");
                for (String confLine : confBodyLines) {
                    int equalsIndex = confLine.indexOf("=");
                    if (equalsIndex != -1) {
                        String key = confLine.substring(0, equalsIndex).trim();
                        String value = confLine.substring(equalsIndex + 1).trim();
                        updateConf.put(key, value);
                    } else {
                        logger.debug("Could not parse line:  ignoring:  '" + confLine + "'");
                    }
                }
            }
            boolean isUpdate = "update".equals(meta);
            for (Object keyObject : updateConf.keySet()) {
                String key = (String) keyObject;
                if (isUpdate && key.startsWith("+")) {
                    String newKey = key.substring(1);

                    // only add if doesn't already exist
                    if (conf.get(newKey) == null) {
                        conf.put(newKey, castValueIfNecessary(updateConf.get(key)));
                    }

                } else if (isUpdate && key.startsWith("-")) {
                    key = key.substring(1);

                    // remove key
                    conf.remove(key);
                } else {
                    // add or overwrite existing property
                    conf.put(key, castToMatchExistingTypeIfNecessary(updateConf.get(key), conf.get(key)));
                }
            } // for

            putConf(clusterId, relativePath, conf);

            // set if it's a "put"
            responseMessage.setBody(conf);

        } else if ("delete".equals(meta)) {
            logger.info("DELETE configuration:  clusterId={}; path={}", clusterId, relativePath);

            // delete conf
            removeConf(clusterId, relativePath);

        } else {
            responseMessage.setComment("Invalid request (do not understand '" + meta + "'):  " + requestBody);
        }

    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.NONODE) {
            if (logger.isDebugEnabled()) {
                logger.debug("" + e, e);
            }
            responseMessage.setStatus(ResponseStatus.OK, "No configuration found.");
        } else {
            responseMessage.setStatus(ResponseStatus.ERROR_UNEXPECTED, "" + e);
        }
    } catch (Exception e) {
        logger.error("handleMessage():  " + e, e);
        responseMessage.setStatus(ResponseStatus.ERROR_UNEXPECTED, "" + e);
    }

    responseMessage.setId(requestMessage.getId());

    return responseMessage;
}

From source file:io.reign.coord.CoordinationService.java

License:Apache License

public List<String> getLocks(String clusterId) {
    String path = getPathScheme().getAbsolutePath(PathType.COORD, clusterId,
            ReservationType.LOCK_EXCLUSIVE.category());
    List<String> children = Collections.EMPTY_LIST;
    try {/* w w  w .  j a va 2  s.  c om*/
        Stat stat = new Stat();
        children = getZkClient().getChildren(path, true, stat);

    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            logger.warn("getLocks():  " + e + ":  node does not exist:  path={}", path);
        } else {
            logger.warn("getLocks():  " + e, e);
        }
        return Collections.EMPTY_LIST;
    } catch (InterruptedException e) {
        logger.warn("lookupClusters():  " + e, e);
        return Collections.EMPTY_LIST;
    }

    return children != null ? children : Collections.EMPTY_LIST;
}