public static List<String> listKeys(KeyValueClient kv, String keyPrefix) { try { return kv.getKeys(keyPrefix); } catch (ConsulException e) { if (e.getCode() == HTTP_NOT_FOUND) { return new ArrayList<>(0); } throw e; } }
/** * Retrieves a {@link com.orbitz.consul.model.kv.Value} for a specific key * from the key/value store. * * GET /v1/kv/{key} * * @param key The key to retrieve. * @param queryOptions The query options. * @return An {@link Optional} containing the value or {@link Optional#empty()()} */ public Optional<Value> getValue(String key, QueryOptions queryOptions) { try { return getSingleValue(http.extract(api.getValue(trimLeadingSlash(key), queryOptions.toQuery()), NOT_FOUND_404)); } catch (ConsulException ignored) { if(ignored.getCode() != NOT_FOUND_404) { throw ignored; } } return Optional.empty(); }
/** * Returns a {@link ConsulResponse<Value>} for a specific key from the kv store. * Contains the consul response headers along with the configuration value. * * GET /v1/kv/{key} * * @param key The key to retrieve. * @param queryOptions The query options. * @return An {@link Optional} containing the ConsulResponse or {@link Optional#empty()} */ public Optional<ConsulResponse<Value>> getConsulResponseWithValue(String key, QueryOptions queryOptions) { try { ConsulResponse<List<Value>> consulResponse = http.extractConsulResponse(api.getValue(trimLeadingSlash(key), queryOptions.toQuery()), NOT_FOUND_404); Optional<Value> consulValue = getSingleValue(consulResponse.getResponse()); if (consulValue.isPresent()) { ConsulResponse<Value> result = new ConsulResponse<>(consulValue.get(), consulResponse.getLastContact(), consulResponse.isKnownLeader(), consulResponse.getIndex()); return Optional.of(result); } } catch (ConsulException ignored) { if (ignored.getCode() != NOT_FOUND_404) { throw ignored; } } return Optional.empty(); }
/** * Returns {@code true} if the given session owned the lock, otherwise {@code false}. */ public static boolean unlockAndDelete(KeyValueClient kv, String key, String sessionId) { try { kv.performTransaction( ImmutableOperation.builder(Verb.UNLOCK).key(key).session(sessionId).build(), ImmutableOperation.builder(Verb.DELETE).key(key).build()); return true; } catch (ConsulException e) { if (e.getCode() == HTTP_CONFLICT) { return false; // didn't own lock; no worries } throw e; } }