Java Code Examples for io.etcd.jetcd.ByteSequence#from()

The following examples show how to use io.etcd.jetcd.ByteSequence#from() . 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: Main.java    From jetcd with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) {
    Args cmd = new Args();

    JCommander.newBuilder().addObject(cmd).build().parse(args);

    CountDownLatch latch = new CountDownLatch(cmd.maxEvents);
    ByteSequence key = ByteSequence.from(cmd.key, StandardCharsets.UTF_8);
    Collection<URI> endpoints = Util.toURIs(cmd.endpoints);

    Watch.Listener listener = Watch.listener(response -> {
        LOGGER.info("Watching for key={}", cmd.key);

        for (WatchEvent event : response.getEvents()) {
            LOGGER.info("type={}, key={}, value={}", event.getEventType(),
                Optional.ofNullable(event.getKeyValue().getKey()).map(bs -> bs.toString(StandardCharsets.UTF_8)).orElse(""),
                Optional.ofNullable(event.getKeyValue().getValue()).map(bs -> bs.toString(StandardCharsets.UTF_8))
                    .orElse(""));
        }

        latch.countDown();
    });

    try (Client client = Client.builder().endpoints(endpoints).build();
        Watch watch = client.getWatchClient();
        Watch.Watcher watcher = watch.watch(key, listener)) {

        latch.await();
    } catch (Exception e) {
        LOGGER.error("Watching Error {}", e);
        System.exit(1);
    }
}
 
Example 2
Source File: AuthRoleGetResponse.java    From jetcd with Apache License 2.0 6 votes vote down vote up
private static Permission toPermission(io.etcd.jetcd.api.Permission perm) {
    ByteSequence key = ByteSequence.from(perm.getKey());
    ByteSequence rangeEnd = ByteSequence.from(perm.getRangeEnd());

    Permission.Type type;
    switch (perm.getPermType()) {
        case READ:
            type = Type.READ;
            break;
        case WRITE:
            type = Type.WRITE;
            break;
        case READWRITE:
            type = Type.READWRITE;
            break;
        default:
            type = Type.UNRECOGNIZED;
    }

    return new Permission(type, key, rangeEnd);
}
 
Example 3
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doRegister(final Registion registion) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (leaseId <= 0) {
        //没有租约
        future.completeExceptionally(new IllegalStateException(
                String.format("Error occurs while register provider of %s, caused by no leaseId. retry....", registion.getService())));
    } else {
        //有租约
        PutOption putOption = PutOption.newBuilder().withLeaseId(leaseId).build();
        ByteSequence key = ByteSequence.from(registion.getPath(), UTF_8);
        ByteSequence value = ByteSequence.from(registion.getUrl().toString(), UTF_8);
        client.getKVClient().put(key, value, putOption).whenComplete((r, t) -> {
            if (!isOpen()) {
                //已经关闭,或者创建了新的客户端
                future.completeExceptionally(new IllegalStateException("controller is closed."));
            } else if (t != null) {
                //TODO 判断租期失效异常,触发重连逻辑
                logger.error(String.format("Error occurs while register provider of %s, caused by %s. retry....",
                        registion.getPath(), t.getMessage()), t);
                future.completeExceptionally(t);
            } else {
                future.complete(null);
            }
        });
    }
    return future;
}
 
Example 4
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doDeregister(final Registion registion) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    ByteSequence key = ByteSequence.from(registion.getPath(), UTF_8);
    client.getKVClient().delete(key).whenComplete((r, t) -> {
        if (t != null) {
            future.completeExceptionally(t);
        } else {
            future.complete(null);
        }
    });
    return future;
}
 
Example 5
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doSubscribe(final ClusterBooking booking) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    EtcdClusterBooking etcdBooking = (EtcdClusterBooking) booking;
    //先查询
    ByteSequence key = ByteSequence.from(etcdBooking.getPath(), UTF_8);
    //先查询,无异常后添加watcher,若结果不为空,通知FULL事件
    GetOption getOption = GetOption.newBuilder().withPrefix(key).build();
    client.getKVClient().get(key, getOption).whenComplete((res, err) -> {
        if (!isOpen()) {
            future.completeExceptionally(new IllegalStateException("controller is closed."));
        } else if (err != null) {
            logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getService(), err.getMessage()), err);
            future.completeExceptionally(err);
        } else {
            List<WatchEvent> events = new ArrayList<>();
            res.getKvs().forEach(kv -> events.add(new WatchEvent(kv, null, PUT)));
            etcdBooking.onUpdate(events, res.getHeader().getRevision(), FULL);
            //添加watch
            try {
                WatchOption watchOption = WatchOption.newBuilder().withPrefix(key).build();
                Watch.Watcher watcher = client.getWatchClient().watch(key, watchOption, etcdBooking);
                etcdBooking.setWatcher(watcher);
                future.complete(null);
            } catch (Exception e) {
                logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getService(), e.getMessage()), e);
                future.completeExceptionally(e);
            }
        }
    });
    return future;
}
 
Example 6
Source File: EtcdRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doSubscribe(final ConfigBooking booking) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    EtcdConfigBooking etcdBooking = (EtcdConfigBooking) booking;
    //先查询
    ByteSequence key = ByteSequence.from(etcdBooking.getPath(), UTF_8);
    //先查询,无异常后添加watcher,若结果不为空,通知FULL事件
    client.getKVClient().get(key).whenComplete((res, err) -> {
        if (!isOpen()) {
            future.completeExceptionally(new IllegalStateException("controller is closed."));
        } else if (err != null) {
            logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getInterface(), err.getMessage()), err);
            future.completeExceptionally(err);
        } else {
            List<WatchEvent> events = new ArrayList<>();
            res.getKvs().forEach(kv -> events.add(new WatchEvent(kv, null, PUT)));
            etcdBooking.onUpdate(events, res.getHeader().getRevision());
            //添加watch
            try {
                WatchOption watchOption = WatchOption.newBuilder().withPrefix(key).build();
                Watch.Watcher watcher = client.getWatchClient().watch(key, watchOption, etcdBooking);
                etcdBooking.setWatcher(watcher);
                future.complete(null);
            } catch (Exception e) {
                logger.error(String.format("Error occurs while subscribe of %s, caused by %s. retry....", etcdBooking.getInterface(), e.getMessage()), e);
                future.completeExceptionally(e);
            }
        }
    });
    return future;
}
 
Example 7
Source File: EtcdCenterRepository.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows({InterruptedException.class, ExecutionException.class})
@Override
public List<String> getChildrenKeys(final String key) {
    String prefix = key + "/";
    ByteSequence prefixByteSequence = ByteSequence.from(prefix, Charsets.UTF_8);
    GetOption getOption = GetOption.newBuilder().withPrefix(prefixByteSequence).withSortField(GetOption.SortTarget.KEY).withSortOrder(GetOption.SortOrder.ASCEND).build();
    List<KeyValue> keyValues = client.getKVClient().get(prefixByteSequence, getOption).get().getKvs();
    return keyValues.stream().map(e -> getSubNodeKeyName(prefix, e.getKey().toString(Charsets.UTF_8))).distinct().collect(Collectors.toList());
}
 
Example 8
Source File: OptionsUtil.java    From jetcd with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the range end of the given prefix.
 *
 * <p>
 * The range end is the key plus one (e.g., "aa"+1 == "ab", "a\xff"+1 == "b").
 *
 * @param  prefix the given prefix
 * @return        the range end of the given prefix
 */
static ByteSequence prefixEndOf(ByteSequence prefix) {
    byte[] endKey = prefix.getBytes().clone();
    for (int i = endKey.length - 1; i >= 0; i--) {
        if (endKey[i] != (byte) 0xff) {
            endKey[i] = (byte) (endKey[i] + 1);
            return ByteSequence.from(Arrays.copyOf(endKey, i + 1));
        }
    }

    return ByteSequence.from(NO_PREFIX_END);
}
 
Example 9
Source File: CommandWatch.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Client client) throws Exception {
    CountDownLatch latch = new CountDownLatch(maxEvents);
    Watcher watcher = null;

    try {
        ByteSequence watchKey = ByteSequence.from(key, Charsets.UTF_8);
        WatchOption watchOpts = WatchOption.newBuilder().withRevision(rev).build();

        watcher = client.getWatchClient().watch(watchKey, watchOpts, response -> {
            for (WatchEvent event : response.getEvents()) {
                LOGGER.info("type={}, key={}, value={}", event.getEventType().toString(),
                    Optional.ofNullable(event.getKeyValue().getKey()).map(bs -> bs.toString(UTF_8)).orElse(""),
                    Optional.ofNullable(event.getKeyValue().getValue()).map(bs -> bs.toString(UTF_8)).orElse(""));
            }

            latch.countDown();
        });

        latch.await();
    } catch (Exception e) {
        if (watcher != null) {
            watcher.close();
        }

        throw e;
    }
}
 
Example 10
Source File: LockResponse.java    From jetcd with Apache License 2.0 4 votes vote down vote up
public LockResponse(io.etcd.jetcd.api.lock.LockResponse response, ByteSequence namespace) {
    super(response, response.getHeader());
    this.unprefixedKey = ByteSequence.from(Util.unprefixNamespace(getResponse().getKey(), namespace));
}