id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
27,600
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.failProbes
private void failProbes(ImmutableMember suspect) { SwimMember swimMember = new SwimMember(suspect); LOGGER.debug("{} - Failed all probes of {}", localMember.id(), swimMember); swimMember.setState(State.SUSPECT); if (updateState(swimMember.copy()) && config.isBroadcastUpdates()) { broadcast(swimMember.copy()); } }
java
private void failProbes(ImmutableMember suspect) { SwimMember swimMember = new SwimMember(suspect); LOGGER.debug("{} - Failed all probes of {}", localMember.id(), swimMember); swimMember.setState(State.SUSPECT); if (updateState(swimMember.copy()) && config.isBroadcastUpdates()) { broadcast(swimMember.copy()); } }
[ "private", "void", "failProbes", "(", "ImmutableMember", "suspect", ")", "{", "SwimMember", "swimMember", "=", "new", "SwimMember", "(", "suspect", ")", ";", "LOGGER", ".", "debug", "(", "\"{} - Failed all probes of {}\"", ",", "localMember", ".", "id", "(", ")", ",", "swimMember", ")", ";", "swimMember", ".", "setState", "(", "State", ".", "SUSPECT", ")", ";", "if", "(", "updateState", "(", "swimMember", ".", "copy", "(", ")", ")", "&&", "config", ".", "isBroadcastUpdates", "(", ")", ")", "{", "broadcast", "(", "swimMember", ".", "copy", "(", ")", ")", ";", "}", "}" ]
Marks the given member suspect after all probes failing.
[ "Marks", "the", "given", "member", "suspect", "after", "all", "probes", "failing", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L491-L498
27,601
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.requestProbe
private CompletableFuture<Boolean> requestProbe(SwimMember member, ImmutableMember suspect) { LOGGER.debug("{} - Requesting probe of {} from {}", this.localMember.id(), suspect, member); return bootstrapService.getMessagingService().sendAndReceive( member.address(), MEMBERSHIP_PROBE_REQUEST, SERIALIZER.encode(suspect), false, config.getProbeTimeout().multipliedBy(2)) .<Boolean>thenApply(SERIALIZER::decode) .<Boolean>exceptionally(e -> false) .thenApply(succeeded -> { LOGGER.debug("{} - Probe request of {} from {} {}", localMember.id(), suspect, member, succeeded ? "succeeded" : "failed"); return succeeded; }); }
java
private CompletableFuture<Boolean> requestProbe(SwimMember member, ImmutableMember suspect) { LOGGER.debug("{} - Requesting probe of {} from {}", this.localMember.id(), suspect, member); return bootstrapService.getMessagingService().sendAndReceive( member.address(), MEMBERSHIP_PROBE_REQUEST, SERIALIZER.encode(suspect), false, config.getProbeTimeout().multipliedBy(2)) .<Boolean>thenApply(SERIALIZER::decode) .<Boolean>exceptionally(e -> false) .thenApply(succeeded -> { LOGGER.debug("{} - Probe request of {} from {} {}", localMember.id(), suspect, member, succeeded ? "succeeded" : "failed"); return succeeded; }); }
[ "private", "CompletableFuture", "<", "Boolean", ">", "requestProbe", "(", "SwimMember", "member", ",", "ImmutableMember", "suspect", ")", "{", "LOGGER", ".", "debug", "(", "\"{} - Requesting probe of {} from {}\"", ",", "this", ".", "localMember", ".", "id", "(", ")", ",", "suspect", ",", "member", ")", ";", "return", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "sendAndReceive", "(", "member", ".", "address", "(", ")", ",", "MEMBERSHIP_PROBE_REQUEST", ",", "SERIALIZER", ".", "encode", "(", "suspect", ")", ",", "false", ",", "config", ".", "getProbeTimeout", "(", ")", ".", "multipliedBy", "(", "2", ")", ")", ".", "<", "Boolean", ">", "thenApply", "(", "SERIALIZER", "::", "decode", ")", ".", "<", "Boolean", ">", "exceptionally", "(", "e", "->", "false", ")", ".", "thenApply", "(", "succeeded", "->", "{", "LOGGER", ".", "debug", "(", "\"{} - Probe request of {} from {} {}\"", ",", "localMember", ".", "id", "(", ")", ",", "suspect", ",", "member", ",", "succeeded", "?", "\"succeeded\"", ":", "\"failed\"", ")", ";", "return", "succeeded", ";", "}", ")", ";", "}" ]
Requests a probe of the given suspect from the given member. @param member the member to perform the probe @param suspect the suspect member to probe
[ "Requests", "a", "probe", "of", "the", "given", "suspect", "from", "the", "given", "member", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L506-L516
27,602
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.selectRandomMembers
private Collection<SwimMember> selectRandomMembers(int count, ImmutableMember exclude) { List<SwimMember> members = this.members.values().stream() .filter(member -> !member.id().equals(localMember.id()) && !member.id().equals(exclude.id())) .collect(Collectors.toList()); Collections.shuffle(members); return members.subList(0, Math.min(members.size(), count)); }
java
private Collection<SwimMember> selectRandomMembers(int count, ImmutableMember exclude) { List<SwimMember> members = this.members.values().stream() .filter(member -> !member.id().equals(localMember.id()) && !member.id().equals(exclude.id())) .collect(Collectors.toList()); Collections.shuffle(members); return members.subList(0, Math.min(members.size(), count)); }
[ "private", "Collection", "<", "SwimMember", ">", "selectRandomMembers", "(", "int", "count", ",", "ImmutableMember", "exclude", ")", "{", "List", "<", "SwimMember", ">", "members", "=", "this", ".", "members", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "member", "->", "!", "member", ".", "id", "(", ")", ".", "equals", "(", "localMember", ".", "id", "(", ")", ")", "&&", "!", "member", ".", "id", "(", ")", ".", "equals", "(", "exclude", ".", "id", "(", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "Collections", ".", "shuffle", "(", "members", ")", ";", "return", "members", ".", "subList", "(", "0", ",", "Math", ".", "min", "(", "members", ".", "size", "(", ")", ",", "count", ")", ")", ";", "}" ]
Selects a set of random members, excluding the local member and a given member. @param count count the number of random members to select @param exclude the member to exclude @return members a set of random members
[ "Selects", "a", "set", "of", "random", "members", "excluding", "the", "local", "member", "and", "a", "given", "member", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L525-L531
27,603
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.handleProbeRequest
private CompletableFuture<Boolean> handleProbeRequest(ImmutableMember member) { CompletableFuture<Boolean> future = new CompletableFuture<>(); swimScheduler.execute(() -> { LOGGER.trace("{} - Probing {}", localMember.id(), member); bootstrapService.getMessagingService().sendAndReceive( member.address(), MEMBERSHIP_PROBE, SERIALIZER.encode(Pair.of(localMember.copy(), member)), false, config.getProbeTimeout()) .whenCompleteAsync((response, error) -> { if (error != null) { LOGGER.debug("{} - Failed to probe {}", localMember.id(), member); future.complete(false); } else { future.complete(true); } }, swimScheduler); }); return future; }
java
private CompletableFuture<Boolean> handleProbeRequest(ImmutableMember member) { CompletableFuture<Boolean> future = new CompletableFuture<>(); swimScheduler.execute(() -> { LOGGER.trace("{} - Probing {}", localMember.id(), member); bootstrapService.getMessagingService().sendAndReceive( member.address(), MEMBERSHIP_PROBE, SERIALIZER.encode(Pair.of(localMember.copy(), member)), false, config.getProbeTimeout()) .whenCompleteAsync((response, error) -> { if (error != null) { LOGGER.debug("{} - Failed to probe {}", localMember.id(), member); future.complete(false); } else { future.complete(true); } }, swimScheduler); }); return future; }
[ "private", "CompletableFuture", "<", "Boolean", ">", "handleProbeRequest", "(", "ImmutableMember", "member", ")", "{", "CompletableFuture", "<", "Boolean", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "swimScheduler", ".", "execute", "(", "(", ")", "->", "{", "LOGGER", ".", "trace", "(", "\"{} - Probing {}\"", ",", "localMember", ".", "id", "(", ")", ",", "member", ")", ";", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "sendAndReceive", "(", "member", ".", "address", "(", ")", ",", "MEMBERSHIP_PROBE", ",", "SERIALIZER", ".", "encode", "(", "Pair", ".", "of", "(", "localMember", ".", "copy", "(", ")", ",", "member", ")", ")", ",", "false", ",", "config", ".", "getProbeTimeout", "(", ")", ")", ".", "whenCompleteAsync", "(", "(", "response", ",", "error", ")", "->", "{", "if", "(", "error", "!=", "null", ")", "{", "LOGGER", ".", "debug", "(", "\"{} - Failed to probe {}\"", ",", "localMember", ".", "id", "(", ")", ",", "member", ")", ";", "future", ".", "complete", "(", "false", ")", ";", "}", "else", "{", "future", ".", "complete", "(", "true", ")", ";", "}", "}", ",", "swimScheduler", ")", ";", "}", ")", ";", "return", "future", ";", "}" ]
Handles a probe request. @param member the member to probe
[ "Handles", "a", "probe", "request", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L538-L554
27,604
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.broadcast
private void broadcast(ImmutableMember update) { for (SwimMember member : members.values()) { if (!localMember.id().equals(member.id())) { unicast(member, update); } } }
java
private void broadcast(ImmutableMember update) { for (SwimMember member : members.values()) { if (!localMember.id().equals(member.id())) { unicast(member, update); } } }
[ "private", "void", "broadcast", "(", "ImmutableMember", "update", ")", "{", "for", "(", "SwimMember", "member", ":", "members", ".", "values", "(", ")", ")", "{", "if", "(", "!", "localMember", ".", "id", "(", ")", ".", "equals", "(", "member", ".", "id", "(", ")", ")", ")", "{", "unicast", "(", "member", ",", "update", ")", ";", "}", "}", "}" ]
Broadcasts the given update to all peers. @param update the update to broadcast
[ "Broadcasts", "the", "given", "update", "to", "all", "peers", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L561-L567
27,605
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.unicast
private void unicast(SwimMember member, ImmutableMember update) { bootstrapService.getUnicastService().unicast( member.address(), MEMBERSHIP_GOSSIP, SERIALIZER.encode(Lists.newArrayList(update))); }
java
private void unicast(SwimMember member, ImmutableMember update) { bootstrapService.getUnicastService().unicast( member.address(), MEMBERSHIP_GOSSIP, SERIALIZER.encode(Lists.newArrayList(update))); }
[ "private", "void", "unicast", "(", "SwimMember", "member", ",", "ImmutableMember", "update", ")", "{", "bootstrapService", ".", "getUnicastService", "(", ")", ".", "unicast", "(", "member", ".", "address", "(", ")", ",", "MEMBERSHIP_GOSSIP", ",", "SERIALIZER", ".", "encode", "(", "Lists", ".", "newArrayList", "(", "update", ")", ")", ")", ";", "}" ]
Unicasts the given update to the given member. @param member the member to which to unicast the update @param update the update to unicast
[ "Unicasts", "the", "given", "update", "to", "the", "given", "member", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L575-L580
27,606
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.gossip
private void gossip() { // Check suspect nodes for failure timeouts. checkFailures(); // Check local metadata for changes. checkMetadata(); // Copy and clear the list of pending updates. if (!updates.isEmpty()) { List<ImmutableMember> updates = Lists.newArrayList(this.updates.values()); this.updates.clear(); // Gossip the pending updates to peers. gossip(updates); } }
java
private void gossip() { // Check suspect nodes for failure timeouts. checkFailures(); // Check local metadata for changes. checkMetadata(); // Copy and clear the list of pending updates. if (!updates.isEmpty()) { List<ImmutableMember> updates = Lists.newArrayList(this.updates.values()); this.updates.clear(); // Gossip the pending updates to peers. gossip(updates); } }
[ "private", "void", "gossip", "(", ")", "{", "// Check suspect nodes for failure timeouts.", "checkFailures", "(", ")", ";", "// Check local metadata for changes.", "checkMetadata", "(", ")", ";", "// Copy and clear the list of pending updates.", "if", "(", "!", "updates", ".", "isEmpty", "(", ")", ")", "{", "List", "<", "ImmutableMember", ">", "updates", "=", "Lists", ".", "newArrayList", "(", "this", ".", "updates", ".", "values", "(", ")", ")", ";", "this", ".", "updates", ".", "clear", "(", ")", ";", "// Gossip the pending updates to peers.", "gossip", "(", "updates", ")", ";", "}", "}" ]
Gossips pending updates to the cluster.
[ "Gossips", "pending", "updates", "to", "the", "cluster", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L585-L600
27,607
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.gossip
private void gossip(Collection<ImmutableMember> updates) { // Get a list of available peers. If peers are available, randomize the peer list and select a subset of // peers with which to gossip updates. List<SwimMember> members = Lists.newArrayList(randomMembers); if (!members.isEmpty()) { Collections.shuffle(members); for (int i = 0; i < Math.min(members.size(), config.getGossipFanout()); i++) { gossip(members.get(i), updates); } } }
java
private void gossip(Collection<ImmutableMember> updates) { // Get a list of available peers. If peers are available, randomize the peer list and select a subset of // peers with which to gossip updates. List<SwimMember> members = Lists.newArrayList(randomMembers); if (!members.isEmpty()) { Collections.shuffle(members); for (int i = 0; i < Math.min(members.size(), config.getGossipFanout()); i++) { gossip(members.get(i), updates); } } }
[ "private", "void", "gossip", "(", "Collection", "<", "ImmutableMember", ">", "updates", ")", "{", "// Get a list of available peers. If peers are available, randomize the peer list and select a subset of", "// peers with which to gossip updates.", "List", "<", "SwimMember", ">", "members", "=", "Lists", ".", "newArrayList", "(", "randomMembers", ")", ";", "if", "(", "!", "members", ".", "isEmpty", "(", ")", ")", "{", "Collections", ".", "shuffle", "(", "members", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Math", ".", "min", "(", "members", ".", "size", "(", ")", ",", "config", ".", "getGossipFanout", "(", ")", ")", ";", "i", "++", ")", "{", "gossip", "(", "members", ".", "get", "(", "i", ")", ",", "updates", ")", ";", "}", "}", "}" ]
Gossips this node's pending updates with a random set of peers. @param updates a collection of updated to gossip
[ "Gossips", "this", "node", "s", "pending", "updates", "with", "a", "random", "set", "of", "peers", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L607-L617
27,608
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.gossip
private void gossip(SwimMember member, Collection<ImmutableMember> updates) { LOGGER.trace("{} - Gossipping updates {} to {}", localMember.id(), updates, member); bootstrapService.getUnicastService().unicast( member.address(), MEMBERSHIP_GOSSIP, SERIALIZER.encode(updates)); }
java
private void gossip(SwimMember member, Collection<ImmutableMember> updates) { LOGGER.trace("{} - Gossipping updates {} to {}", localMember.id(), updates, member); bootstrapService.getUnicastService().unicast( member.address(), MEMBERSHIP_GOSSIP, SERIALIZER.encode(updates)); }
[ "private", "void", "gossip", "(", "SwimMember", "member", ",", "Collection", "<", "ImmutableMember", ">", "updates", ")", "{", "LOGGER", ".", "trace", "(", "\"{} - Gossipping updates {} to {}\"", ",", "localMember", ".", "id", "(", ")", ",", "updates", ",", "member", ")", ";", "bootstrapService", ".", "getUnicastService", "(", ")", ".", "unicast", "(", "member", ".", "address", "(", ")", ",", "MEMBERSHIP_GOSSIP", ",", "SERIALIZER", ".", "encode", "(", "updates", ")", ")", ";", "}" ]
Gossips this node's pending updates with the given peer. @param member the peer with which to gossip this node's updates @param updates the updated members to gossip
[ "Gossips", "this", "node", "s", "pending", "updates", "with", "the", "given", "peer", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L625-L631
27,609
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.registerHandlers
private void registerHandlers() { // Register TCP message handlers. bootstrapService.getMessagingService().registerHandler(MEMBERSHIP_SYNC, syncHandler, swimScheduler); bootstrapService.getMessagingService().registerHandler(MEMBERSHIP_PROBE, probeHandler, swimScheduler); bootstrapService.getMessagingService().registerHandler(MEMBERSHIP_PROBE_REQUEST, probeRequestHandler); // Register UDP message listeners. bootstrapService.getUnicastService().addListener(MEMBERSHIP_GOSSIP, gossipListener, swimScheduler); }
java
private void registerHandlers() { // Register TCP message handlers. bootstrapService.getMessagingService().registerHandler(MEMBERSHIP_SYNC, syncHandler, swimScheduler); bootstrapService.getMessagingService().registerHandler(MEMBERSHIP_PROBE, probeHandler, swimScheduler); bootstrapService.getMessagingService().registerHandler(MEMBERSHIP_PROBE_REQUEST, probeRequestHandler); // Register UDP message listeners. bootstrapService.getUnicastService().addListener(MEMBERSHIP_GOSSIP, gossipListener, swimScheduler); }
[ "private", "void", "registerHandlers", "(", ")", "{", "// Register TCP message handlers.", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "registerHandler", "(", "MEMBERSHIP_SYNC", ",", "syncHandler", ",", "swimScheduler", ")", ";", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "registerHandler", "(", "MEMBERSHIP_PROBE", ",", "probeHandler", ",", "swimScheduler", ")", ";", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "registerHandler", "(", "MEMBERSHIP_PROBE_REQUEST", ",", "probeRequestHandler", ")", ";", "// Register UDP message listeners.", "bootstrapService", ".", "getUnicastService", "(", ")", ".", "addListener", "(", "MEMBERSHIP_GOSSIP", ",", "gossipListener", ",", "swimScheduler", ")", ";", "}" ]
Registers message handlers for the SWIM protocol.
[ "Registers", "message", "handlers", "for", "the", "SWIM", "protocol", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L683-L691
27,610
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java
SwimMembershipProtocol.unregisterHandlers
private void unregisterHandlers() { // Unregister TCP message handlers. bootstrapService.getMessagingService().unregisterHandler(MEMBERSHIP_SYNC); bootstrapService.getMessagingService().unregisterHandler(MEMBERSHIP_PROBE); bootstrapService.getMessagingService().unregisterHandler(MEMBERSHIP_PROBE_REQUEST); // Unregister UDP message listeners. bootstrapService.getUnicastService().removeListener(MEMBERSHIP_GOSSIP, gossipListener); }
java
private void unregisterHandlers() { // Unregister TCP message handlers. bootstrapService.getMessagingService().unregisterHandler(MEMBERSHIP_SYNC); bootstrapService.getMessagingService().unregisterHandler(MEMBERSHIP_PROBE); bootstrapService.getMessagingService().unregisterHandler(MEMBERSHIP_PROBE_REQUEST); // Unregister UDP message listeners. bootstrapService.getUnicastService().removeListener(MEMBERSHIP_GOSSIP, gossipListener); }
[ "private", "void", "unregisterHandlers", "(", ")", "{", "// Unregister TCP message handlers.", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "unregisterHandler", "(", "MEMBERSHIP_SYNC", ")", ";", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "unregisterHandler", "(", "MEMBERSHIP_PROBE", ")", ";", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "unregisterHandler", "(", "MEMBERSHIP_PROBE_REQUEST", ")", ";", "// Unregister UDP message listeners.", "bootstrapService", ".", "getUnicastService", "(", ")", ".", "removeListener", "(", "MEMBERSHIP_GOSSIP", ",", "gossipListener", ")", ";", "}" ]
Unregisters handlers for the SWIM protocol.
[ "Unregisters", "handlers", "for", "the", "SWIM", "protocol", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java#L696-L704
27,611
atomix/atomix
core/src/main/java/io/atomix/core/semaphore/impl/AtomicSemaphoreProxy.java
AtomicSemaphoreProxy.holderStatus
public CompletableFuture<Map<Long, Integer>> holderStatus() { return getProxyClient().applyBy(name(), service -> service.holderStatus()); }
java
public CompletableFuture<Map<Long, Integer>> holderStatus() { return getProxyClient().applyBy(name(), service -> service.holderStatus()); }
[ "public", "CompletableFuture", "<", "Map", "<", "Long", ",", "Integer", ">", ">", "holderStatus", "(", ")", "{", "return", "getProxyClient", "(", ")", ".", "applyBy", "(", "name", "(", ")", ",", "service", "->", "service", ".", "holderStatus", "(", ")", ")", ";", "}" ]
Query all permit holders. For debugging only. @return CompletableFuture that is completed with the current permit holders
[ "Query", "all", "permit", "holders", ".", "For", "debugging", "only", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/semaphore/impl/AtomicSemaphoreProxy.java#L176-L178
27,612
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderAppender.java
LeaderAppender.recordHeartbeat
private void recordHeartbeat(RaftMemberContext member, long timestamp) { raft.checkThread(); // Update the member's heartbeat time. This will be used when calculating the quorum heartbeat time. member.setHeartbeatTime(timestamp); member.setResponseTime(System.currentTimeMillis()); // Compute the quorum heartbeat time. long heartbeatTime = computeHeartbeatTime(); long currentTimestamp = System.currentTimeMillis(); // Iterate through pending timestamped heartbeat futures and complete all futures where the timestamp // is greater than the last timestamp a quorum of the cluster was contacted. Iterator<TimestampedFuture<Long>> iterator = heartbeatFutures.iterator(); while (iterator.hasNext()) { TimestampedFuture<Long> future = iterator.next(); // If the future is timestamped prior to the last heartbeat to a majority of the cluster, complete the future. if (future.timestamp < heartbeatTime) { future.complete(null); iterator.remove(); } // If the future is more than an election timeout old, fail it with a protocol exception. else if (currentTimestamp - future.timestamp > electionTimeout) { future.completeExceptionally(new RaftException.ProtocolException("Failed to reach consensus")); iterator.remove(); } // Otherwise, we've reached recent heartbeat futures. Break out of the loop. else { break; } } // If heartbeat futures are still pending, attempt to send heartbeats. if (!heartbeatFutures.isEmpty()) { sendHeartbeats(); } }
java
private void recordHeartbeat(RaftMemberContext member, long timestamp) { raft.checkThread(); // Update the member's heartbeat time. This will be used when calculating the quorum heartbeat time. member.setHeartbeatTime(timestamp); member.setResponseTime(System.currentTimeMillis()); // Compute the quorum heartbeat time. long heartbeatTime = computeHeartbeatTime(); long currentTimestamp = System.currentTimeMillis(); // Iterate through pending timestamped heartbeat futures and complete all futures where the timestamp // is greater than the last timestamp a quorum of the cluster was contacted. Iterator<TimestampedFuture<Long>> iterator = heartbeatFutures.iterator(); while (iterator.hasNext()) { TimestampedFuture<Long> future = iterator.next(); // If the future is timestamped prior to the last heartbeat to a majority of the cluster, complete the future. if (future.timestamp < heartbeatTime) { future.complete(null); iterator.remove(); } // If the future is more than an election timeout old, fail it with a protocol exception. else if (currentTimestamp - future.timestamp > electionTimeout) { future.completeExceptionally(new RaftException.ProtocolException("Failed to reach consensus")); iterator.remove(); } // Otherwise, we've reached recent heartbeat futures. Break out of the loop. else { break; } } // If heartbeat futures are still pending, attempt to send heartbeats. if (!heartbeatFutures.isEmpty()) { sendHeartbeats(); } }
[ "private", "void", "recordHeartbeat", "(", "RaftMemberContext", "member", ",", "long", "timestamp", ")", "{", "raft", ".", "checkThread", "(", ")", ";", "// Update the member's heartbeat time. This will be used when calculating the quorum heartbeat time.", "member", ".", "setHeartbeatTime", "(", "timestamp", ")", ";", "member", ".", "setResponseTime", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "// Compute the quorum heartbeat time.", "long", "heartbeatTime", "=", "computeHeartbeatTime", "(", ")", ";", "long", "currentTimestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "// Iterate through pending timestamped heartbeat futures and complete all futures where the timestamp", "// is greater than the last timestamp a quorum of the cluster was contacted.", "Iterator", "<", "TimestampedFuture", "<", "Long", ">", ">", "iterator", "=", "heartbeatFutures", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "TimestampedFuture", "<", "Long", ">", "future", "=", "iterator", ".", "next", "(", ")", ";", "// If the future is timestamped prior to the last heartbeat to a majority of the cluster, complete the future.", "if", "(", "future", ".", "timestamp", "<", "heartbeatTime", ")", "{", "future", ".", "complete", "(", "null", ")", ";", "iterator", ".", "remove", "(", ")", ";", "}", "// If the future is more than an election timeout old, fail it with a protocol exception.", "else", "if", "(", "currentTimestamp", "-", "future", ".", "timestamp", ">", "electionTimeout", ")", "{", "future", ".", "completeExceptionally", "(", "new", "RaftException", ".", "ProtocolException", "(", "\"Failed to reach consensus\"", ")", ")", ";", "iterator", ".", "remove", "(", ")", ";", "}", "// Otherwise, we've reached recent heartbeat futures. Break out of the loop.", "else", "{", "break", ";", "}", "}", "// If heartbeat futures are still pending, attempt to send heartbeats.", "if", "(", "!", "heartbeatFutures", ".", "isEmpty", "(", ")", ")", "{", "sendHeartbeats", "(", ")", ";", "}", "}" ]
Records a completed heartbeat to the given member.
[ "Records", "a", "completed", "heartbeat", "to", "the", "given", "member", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderAppender.java#L246-L283
27,613
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderAppender.java
LeaderAppender.failHeartbeat
private void failHeartbeat() { raft.checkThread(); // Iterate through pending timestamped heartbeat futures and fail futures that have been pending longer // than an election timeout. long currentTimestamp = System.currentTimeMillis(); Iterator<TimestampedFuture<Long>> iterator = heartbeatFutures.iterator(); while (iterator.hasNext()) { TimestampedFuture<Long> future = iterator.next(); if (currentTimestamp - future.timestamp > electionTimeout) { future.completeExceptionally(new RaftException.ProtocolException("Failed to reach consensus")); iterator.remove(); } } }
java
private void failHeartbeat() { raft.checkThread(); // Iterate through pending timestamped heartbeat futures and fail futures that have been pending longer // than an election timeout. long currentTimestamp = System.currentTimeMillis(); Iterator<TimestampedFuture<Long>> iterator = heartbeatFutures.iterator(); while (iterator.hasNext()) { TimestampedFuture<Long> future = iterator.next(); if (currentTimestamp - future.timestamp > electionTimeout) { future.completeExceptionally(new RaftException.ProtocolException("Failed to reach consensus")); iterator.remove(); } } }
[ "private", "void", "failHeartbeat", "(", ")", "{", "raft", ".", "checkThread", "(", ")", ";", "// Iterate through pending timestamped heartbeat futures and fail futures that have been pending longer", "// than an election timeout.", "long", "currentTimestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "Iterator", "<", "TimestampedFuture", "<", "Long", ">", ">", "iterator", "=", "heartbeatFutures", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "TimestampedFuture", "<", "Long", ">", "future", "=", "iterator", ".", "next", "(", ")", ";", "if", "(", "currentTimestamp", "-", "future", ".", "timestamp", ">", "electionTimeout", ")", "{", "future", ".", "completeExceptionally", "(", "new", "RaftException", ".", "ProtocolException", "(", "\"Failed to reach consensus\"", ")", ")", ";", "iterator", ".", "remove", "(", ")", ";", "}", "}", "}" ]
Records a failed heartbeat.
[ "Records", "a", "failed", "heartbeat", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderAppender.java#L288-L302
27,614
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderAppender.java
LeaderAppender.completeCommits
private void completeCommits(long previousCommitIndex, long commitIndex) { for (long i = previousCommitIndex + 1; i <= commitIndex; i++) { CompletableFuture<Long> future = appendFutures.remove(i); if (future != null) { future.complete(i); } } }
java
private void completeCommits(long previousCommitIndex, long commitIndex) { for (long i = previousCommitIndex + 1; i <= commitIndex; i++) { CompletableFuture<Long> future = appendFutures.remove(i); if (future != null) { future.complete(i); } } }
[ "private", "void", "completeCommits", "(", "long", "previousCommitIndex", ",", "long", "commitIndex", ")", "{", "for", "(", "long", "i", "=", "previousCommitIndex", "+", "1", ";", "i", "<=", "commitIndex", ";", "i", "++", ")", "{", "CompletableFuture", "<", "Long", ">", "future", "=", "appendFutures", ".", "remove", "(", "i", ")", ";", "if", "(", "future", "!=", "null", ")", "{", "future", ".", "complete", "(", "i", ")", ";", "}", "}", "}" ]
Completes append entries attempts up to the given index.
[ "Completes", "append", "entries", "attempts", "up", "to", "the", "given", "index", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderAppender.java#L354-L361
27,615
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartitionGroup.java
RaftPartitionGroup.snapshot
public CompletableFuture<Void> snapshot() { return Futures.allOf(config.getMembers().stream() .map(MemberId::from) .map(id -> communicationService.send(snapshotSubject, null, id, SNAPSHOT_TIMEOUT)) .collect(Collectors.toList())) .thenApply(v -> null); }
java
public CompletableFuture<Void> snapshot() { return Futures.allOf(config.getMembers().stream() .map(MemberId::from) .map(id -> communicationService.send(snapshotSubject, null, id, SNAPSHOT_TIMEOUT)) .collect(Collectors.toList())) .thenApply(v -> null); }
[ "public", "CompletableFuture", "<", "Void", ">", "snapshot", "(", ")", "{", "return", "Futures", ".", "allOf", "(", "config", ".", "getMembers", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "MemberId", "::", "from", ")", ".", "map", "(", "id", "->", "communicationService", ".", "send", "(", "snapshotSubject", ",", "null", ",", "id", ",", "SNAPSHOT_TIMEOUT", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}" ]
Takes snapshots of all Raft partitions. @return a future to be completed once snapshots have been taken
[ "Takes", "snapshots", "of", "all", "Raft", "partitions", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartitionGroup.java#L213-L219
27,616
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartitionGroup.java
RaftPartitionGroup.handleSnapshot
private CompletableFuture<Void> handleSnapshot() { return Futures.allOf(partitions.values().stream() .map(partition -> partition.snapshot()) .collect(Collectors.toList())) .thenApply(v -> null); }
java
private CompletableFuture<Void> handleSnapshot() { return Futures.allOf(partitions.values().stream() .map(partition -> partition.snapshot()) .collect(Collectors.toList())) .thenApply(v -> null); }
[ "private", "CompletableFuture", "<", "Void", ">", "handleSnapshot", "(", ")", "{", "return", "Futures", ".", "allOf", "(", "partitions", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "partition", "->", "partition", ".", "snapshot", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}" ]
Handles a snapshot request from a peer. @return a future to be completed once the snapshot is complete
[ "Handles", "a", "snapshot", "request", "from", "a", "peer", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartitionGroup.java#L226-L231
27,617
atomix/atomix
core/src/main/java/io/atomix/core/multimap/impl/AbstractAtomicMultimapService.java
AbstractAtomicMultimapService.onChange
private void onChange(String key, byte[] oldValue, byte[] newValue) { listeners.forEach(id -> getSession(id).accept(client -> client.onChange(key, oldValue, newValue))); }
java
private void onChange(String key, byte[] oldValue, byte[] newValue) { listeners.forEach(id -> getSession(id).accept(client -> client.onChange(key, oldValue, newValue))); }
[ "private", "void", "onChange", "(", "String", "key", ",", "byte", "[", "]", "oldValue", ",", "byte", "[", "]", "newValue", ")", "{", "listeners", ".", "forEach", "(", "id", "->", "getSession", "(", "id", ")", ".", "accept", "(", "client", "->", "client", ".", "onChange", "(", "key", ",", "oldValue", ",", "newValue", ")", ")", ")", ";", "}" ]
Sends a change event to listeners. @param key the changed key @param oldValue the old value @param newValue the new value
[ "Sends", "a", "change", "event", "to", "listeners", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/multimap/impl/AbstractAtomicMultimapService.java#L495-L497
27,618
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceSessions.java
PrimaryBackupServiceSessions.openSession
public void openSession(PrimaryBackupSession session) { sessions.put(session.sessionId().id(), session); listeners.forEach(l -> l.onOpen(session)); }
java
public void openSession(PrimaryBackupSession session) { sessions.put(session.sessionId().id(), session); listeners.forEach(l -> l.onOpen(session)); }
[ "public", "void", "openSession", "(", "PrimaryBackupSession", "session", ")", "{", "sessions", ".", "put", "(", "session", ".", "sessionId", "(", ")", ".", "id", "(", ")", ",", "session", ")", ";", "listeners", ".", "forEach", "(", "l", "->", "l", ".", "onOpen", "(", "session", ")", ")", ";", "}" ]
Adds a session to the sessions list. @param session The session to add.
[ "Adds", "a", "session", "to", "the", "sessions", "list", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceSessions.java#L41-L44
27,619
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceSessions.java
PrimaryBackupServiceSessions.expireSession
public void expireSession(PrimaryBackupSession session) { if (sessions.remove(session.sessionId().id()) != null) { session.expire(); listeners.forEach(l -> l.onExpire(session)); } }
java
public void expireSession(PrimaryBackupSession session) { if (sessions.remove(session.sessionId().id()) != null) { session.expire(); listeners.forEach(l -> l.onExpire(session)); } }
[ "public", "void", "expireSession", "(", "PrimaryBackupSession", "session", ")", "{", "if", "(", "sessions", ".", "remove", "(", "session", ".", "sessionId", "(", ")", ".", "id", "(", ")", ")", "!=", "null", ")", "{", "session", ".", "expire", "(", ")", ";", "listeners", ".", "forEach", "(", "l", "->", "l", ".", "onExpire", "(", "session", ")", ")", ";", "}", "}" ]
Expires and removes a session from the sessions list. @param session The session to remove.
[ "Expires", "and", "removes", "a", "session", "from", "the", "sessions", "list", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceSessions.java#L51-L56
27,620
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceSessions.java
PrimaryBackupServiceSessions.closeSession
public void closeSession(PrimaryBackupSession session) { if (sessions.remove(session.sessionId().id()) != null) { session.close(); listeners.forEach(l -> l.onClose(session)); } }
java
public void closeSession(PrimaryBackupSession session) { if (sessions.remove(session.sessionId().id()) != null) { session.close(); listeners.forEach(l -> l.onClose(session)); } }
[ "public", "void", "closeSession", "(", "PrimaryBackupSession", "session", ")", "{", "if", "(", "sessions", ".", "remove", "(", "session", ".", "sessionId", "(", ")", ".", "id", "(", ")", ")", "!=", "null", ")", "{", "session", ".", "close", "(", ")", ";", "listeners", ".", "forEach", "(", "l", "->", "l", ".", "onClose", "(", "session", ")", ")", ";", "}", "}" ]
Closes and removes a session from the sessions list. @param session The session to remove.
[ "Closes", "and", "removes", "a", "session", "from", "the", "sessions", "list", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceSessions.java#L63-L68
27,621
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournalReader.java
SegmentedJournalReader.initialize
private void initialize(long index) { currentSegment = journal.getSegment(index); currentSegment.acquire(); currentReader = currentSegment.createReader(); long nextIndex = getNextIndex(); while (index > nextIndex && hasNext()) { next(); nextIndex = getNextIndex(); } }
java
private void initialize(long index) { currentSegment = journal.getSegment(index); currentSegment.acquire(); currentReader = currentSegment.createReader(); long nextIndex = getNextIndex(); while (index > nextIndex && hasNext()) { next(); nextIndex = getNextIndex(); } }
[ "private", "void", "initialize", "(", "long", "index", ")", "{", "currentSegment", "=", "journal", ".", "getSegment", "(", "index", ")", ";", "currentSegment", ".", "acquire", "(", ")", ";", "currentReader", "=", "currentSegment", ".", "createReader", "(", ")", ";", "long", "nextIndex", "=", "getNextIndex", "(", ")", ";", "while", "(", "index", ">", "nextIndex", "&&", "hasNext", "(", ")", ")", "{", "next", "(", ")", ";", "nextIndex", "=", "getNextIndex", "(", ")", ";", "}", "}" ]
Initializes the reader to the given index.
[ "Initializes", "the", "reader", "to", "the", "given", "index", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournalReader.java#L40-L49
27,622
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournalReader.java
SegmentedJournalReader.rewind
private void rewind(long index) { if (currentSegment.index() >= index) { JournalSegment<E> segment = journal.getSegment(index - 1); if (segment != null) { currentReader.close(); currentSegment.release(); currentSegment = segment; currentSegment.acquire(); currentReader = currentSegment.createReader(); } } currentReader.reset(index); previousEntry = currentReader.getCurrentEntry(); }
java
private void rewind(long index) { if (currentSegment.index() >= index) { JournalSegment<E> segment = journal.getSegment(index - 1); if (segment != null) { currentReader.close(); currentSegment.release(); currentSegment = segment; currentSegment.acquire(); currentReader = currentSegment.createReader(); } } currentReader.reset(index); previousEntry = currentReader.getCurrentEntry(); }
[ "private", "void", "rewind", "(", "long", "index", ")", "{", "if", "(", "currentSegment", ".", "index", "(", ")", ">=", "index", ")", "{", "JournalSegment", "<", "E", ">", "segment", "=", "journal", ".", "getSegment", "(", "index", "-", "1", ")", ";", "if", "(", "segment", "!=", "null", ")", "{", "currentReader", ".", "close", "(", ")", ";", "currentSegment", ".", "release", "(", ")", ";", "currentSegment", "=", "segment", ";", "currentSegment", ".", "acquire", "(", ")", ";", "currentReader", "=", "currentSegment", ".", "createReader", "(", ")", ";", "}", "}", "currentReader", ".", "reset", "(", "index", ")", ";", "previousEntry", "=", "currentReader", ".", "getCurrentEntry", "(", ")", ";", "}" ]
Rewinds the journal to the given index.
[ "Rewinds", "the", "journal", "to", "the", "given", "index", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournalReader.java#L111-L125
27,623
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/impl/OperationResult.java
OperationResult.succeeded
public static OperationResult succeeded(long index, long eventIndex, byte[] result) { return new OperationResult(index, eventIndex, null, result); }
java
public static OperationResult succeeded(long index, long eventIndex, byte[] result) { return new OperationResult(index, eventIndex, null, result); }
[ "public", "static", "OperationResult", "succeeded", "(", "long", "index", ",", "long", "eventIndex", ",", "byte", "[", "]", "result", ")", "{", "return", "new", "OperationResult", "(", "index", ",", "eventIndex", ",", "null", ",", "result", ")", ";", "}" ]
Returns a successful operation result. @param index the result index @param eventIndex the session's last event index @param result the operation result value @return the operation result
[ "Returns", "a", "successful", "operation", "result", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/impl/OperationResult.java#L46-L48
27,624
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/impl/OperationResult.java
OperationResult.failed
public static OperationResult failed(long index, long eventIndex, Throwable error) { return new OperationResult(index, eventIndex, error, null); }
java
public static OperationResult failed(long index, long eventIndex, Throwable error) { return new OperationResult(index, eventIndex, error, null); }
[ "public", "static", "OperationResult", "failed", "(", "long", "index", ",", "long", "eventIndex", ",", "Throwable", "error", ")", "{", "return", "new", "OperationResult", "(", "index", ",", "eventIndex", ",", "error", ",", "null", ")", ";", "}" ]
Returns a failed operation result. @param index the result index @param eventIndex the session's last event index @param error the operation error @return the operation result
[ "Returns", "a", "failed", "operation", "result", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/impl/OperationResult.java#L58-L60
27,625
atomix/atomix
utils/src/main/java/io/atomix/utils/time/Versioned.java
Versioned.map
public synchronized <U> Versioned<U> map(Function<V, U> transformer) { return new Versioned<>(value != null ? transformer.apply(value) : null, version, creationTime); }
java
public synchronized <U> Versioned<U> map(Function<V, U> transformer) { return new Versioned<>(value != null ? transformer.apply(value) : null, version, creationTime); }
[ "public", "synchronized", "<", "U", ">", "Versioned", "<", "U", ">", "map", "(", "Function", "<", "V", ",", "U", ">", "transformer", ")", "{", "return", "new", "Versioned", "<>", "(", "value", "!=", "null", "?", "transformer", ".", "apply", "(", "value", ")", ":", "null", ",", "version", ",", "creationTime", ")", ";", "}" ]
Maps this instance into another after transforming its value while retaining the same version and creationTime. @param transformer function for mapping the value @param <U> value type of the returned instance @return mapped instance
[ "Maps", "this", "instance", "into", "another", "after", "transforming", "its", "value", "while", "retaining", "the", "same", "version", "and", "creationTime", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/time/Versioned.java#L101-L103
27,626
atomix/atomix
utils/src/main/java/io/atomix/utils/time/Versioned.java
Versioned.valueOrElse
public static <U> U valueOrElse(Versioned<U> versioned, U defaultValue) { return versioned == null ? defaultValue : versioned.value(); }
java
public static <U> U valueOrElse(Versioned<U> versioned, U defaultValue) { return versioned == null ? defaultValue : versioned.value(); }
[ "public", "static", "<", "U", ">", "U", "valueOrElse", "(", "Versioned", "<", "U", ">", "versioned", ",", "U", "defaultValue", ")", "{", "return", "versioned", "==", "null", "?", "defaultValue", ":", "versioned", ".", "value", "(", ")", ";", "}" ]
Returns the value of the specified Versioned object if non-null or else returns a default value. @param versioned versioned object @param defaultValue default value to return if versioned object is null @param <U> type of the versioned value @return versioned value or default value if versioned object is null
[ "Returns", "the", "value", "of", "the", "specified", "Versioned", "object", "if", "non", "-", "null", "or", "else", "returns", "a", "default", "value", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/time/Versioned.java#L114-L116
27,627
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/impl/PrimaryBackupMessageContext.java
PrimaryBackupMessageContext.eventSubject
String eventSubject(long sessionId) { if (prefix == null) { return String.format("event-%d", sessionId); } else { return String.format("%s-event-%d", prefix, sessionId); } }
java
String eventSubject(long sessionId) { if (prefix == null) { return String.format("event-%d", sessionId); } else { return String.format("%s-event-%d", prefix, sessionId); } }
[ "String", "eventSubject", "(", "long", "sessionId", ")", "{", "if", "(", "prefix", "==", "null", ")", "{", "return", "String", ".", "format", "(", "\"event-%d\"", ",", "sessionId", ")", ";", "}", "else", "{", "return", "String", ".", "format", "(", "\"%s-event-%d\"", ",", "prefix", ",", "sessionId", ")", ";", "}", "}" ]
Returns the event subject for the given session. @param sessionId the session for which to return the event subject @return the event subject for the given session
[ "Returns", "the", "event", "subject", "for", "the", "given", "session", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/impl/PrimaryBackupMessageContext.java#L48-L54
27,628
atomix/atomix
core/src/main/java/io/atomix/core/utils/config/PolymorphicTypeMapper.java
PolymorphicTypeMapper.getConcreteClass
@SuppressWarnings("unchecked") public Class<? extends TypedConfig<?>> getConcreteClass(AtomixRegistry registry, String typeName) { ConfiguredType type = registry.getType(typeClass, typeName); if (type == null) { return null; } return (Class<? extends TypedConfig<?>>) type.newConfig().getClass(); }
java
@SuppressWarnings("unchecked") public Class<? extends TypedConfig<?>> getConcreteClass(AtomixRegistry registry, String typeName) { ConfiguredType type = registry.getType(typeClass, typeName); if (type == null) { return null; } return (Class<? extends TypedConfig<?>>) type.newConfig().getClass(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "Class", "<", "?", "extends", "TypedConfig", "<", "?", ">", ">", "getConcreteClass", "(", "AtomixRegistry", "registry", ",", "String", "typeName", ")", "{", "ConfiguredType", "type", "=", "registry", ".", "getType", "(", "typeClass", ",", "typeName", ")", ";", "if", "(", "type", "==", "null", ")", "{", "return", "null", ";", "}", "return", "(", "Class", "<", "?", "extends", "TypedConfig", "<", "?", ">", ">", ")", "type", ".", "newConfig", "(", ")", ".", "getClass", "(", ")", ";", "}" ]
Returns the concrete configuration class. @param registry the Atomix type registry @param typeName the type name @return the concrete configuration class
[ "Returns", "the", "concrete", "configuration", "class", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/utils/config/PolymorphicTypeMapper.java#L70-L77
27,629
atomix/atomix
primitive/src/main/java/io/atomix/primitive/partition/impl/PrimaryElectorService.java
PrimaryElectorService.scheduleRebalance
private void scheduleRebalance() { if (rebalanceTimer != null) { rebalanceTimer.cancel(); } rebalanceTimer = getScheduler().schedule(REBALANCE_DURATION, this::rebalance); }
java
private void scheduleRebalance() { if (rebalanceTimer != null) { rebalanceTimer.cancel(); } rebalanceTimer = getScheduler().schedule(REBALANCE_DURATION, this::rebalance); }
[ "private", "void", "scheduleRebalance", "(", ")", "{", "if", "(", "rebalanceTimer", "!=", "null", ")", "{", "rebalanceTimer", ".", "cancel", "(", ")", ";", "}", "rebalanceTimer", "=", "getScheduler", "(", ")", ".", "schedule", "(", "REBALANCE_DURATION", ",", "this", "::", "rebalance", ")", ";", "}" ]
Schedules rebalancing of primaries.
[ "Schedules", "rebalancing", "of", "primaries", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/PrimaryElectorService.java#L115-L120
27,630
atomix/atomix
primitive/src/main/java/io/atomix/primitive/partition/impl/PrimaryElectorService.java
PrimaryElectorService.rebalance
private void rebalance() { boolean rebalanced = false; for (ElectionState election : elections.values()) { // Count the total number of primaries for this election's primary. int primaryCount = election.countPrimaries(election.primary); // Find the registration with the fewest number of primaries. int minCandidateCount = 0; for (Registration candidate : election.registrations) { if (minCandidateCount == 0) { minCandidateCount = election.countPrimaries(candidate); } else { minCandidateCount = Math.min(minCandidateCount, election.countPrimaries(candidate)); } } // If the primary count for the current primary is more than that of the candidate with the fewest // primaries then transfer leadership to the candidate. if (minCandidateCount < primaryCount) { for (Registration candidate : election.registrations) { if (election.countPrimaries(candidate) < primaryCount) { PrimaryTerm oldTerm = election.term(); elections.put(election.partitionId, election.transfer(candidate.member())); PrimaryTerm newTerm = term(election.partitionId); if (!Objects.equals(oldTerm, newTerm)) { notifyTermChange(election.partitionId, newTerm); rebalanced = true; } } } } } // If some elections were rebalanced, reschedule another rebalance after an interval to give the cluster a // change to recognize the primary change and replicate state first. if (rebalanced) { scheduleRebalance(); } }
java
private void rebalance() { boolean rebalanced = false; for (ElectionState election : elections.values()) { // Count the total number of primaries for this election's primary. int primaryCount = election.countPrimaries(election.primary); // Find the registration with the fewest number of primaries. int minCandidateCount = 0; for (Registration candidate : election.registrations) { if (minCandidateCount == 0) { minCandidateCount = election.countPrimaries(candidate); } else { minCandidateCount = Math.min(minCandidateCount, election.countPrimaries(candidate)); } } // If the primary count for the current primary is more than that of the candidate with the fewest // primaries then transfer leadership to the candidate. if (minCandidateCount < primaryCount) { for (Registration candidate : election.registrations) { if (election.countPrimaries(candidate) < primaryCount) { PrimaryTerm oldTerm = election.term(); elections.put(election.partitionId, election.transfer(candidate.member())); PrimaryTerm newTerm = term(election.partitionId); if (!Objects.equals(oldTerm, newTerm)) { notifyTermChange(election.partitionId, newTerm); rebalanced = true; } } } } } // If some elections were rebalanced, reschedule another rebalance after an interval to give the cluster a // change to recognize the primary change and replicate state first. if (rebalanced) { scheduleRebalance(); } }
[ "private", "void", "rebalance", "(", ")", "{", "boolean", "rebalanced", "=", "false", ";", "for", "(", "ElectionState", "election", ":", "elections", ".", "values", "(", ")", ")", "{", "// Count the total number of primaries for this election's primary.", "int", "primaryCount", "=", "election", ".", "countPrimaries", "(", "election", ".", "primary", ")", ";", "// Find the registration with the fewest number of primaries.", "int", "minCandidateCount", "=", "0", ";", "for", "(", "Registration", "candidate", ":", "election", ".", "registrations", ")", "{", "if", "(", "minCandidateCount", "==", "0", ")", "{", "minCandidateCount", "=", "election", ".", "countPrimaries", "(", "candidate", ")", ";", "}", "else", "{", "minCandidateCount", "=", "Math", ".", "min", "(", "minCandidateCount", ",", "election", ".", "countPrimaries", "(", "candidate", ")", ")", ";", "}", "}", "// If the primary count for the current primary is more than that of the candidate with the fewest", "// primaries then transfer leadership to the candidate.", "if", "(", "minCandidateCount", "<", "primaryCount", ")", "{", "for", "(", "Registration", "candidate", ":", "election", ".", "registrations", ")", "{", "if", "(", "election", ".", "countPrimaries", "(", "candidate", ")", "<", "primaryCount", ")", "{", "PrimaryTerm", "oldTerm", "=", "election", ".", "term", "(", ")", ";", "elections", ".", "put", "(", "election", ".", "partitionId", ",", "election", ".", "transfer", "(", "candidate", ".", "member", "(", ")", ")", ")", ";", "PrimaryTerm", "newTerm", "=", "term", "(", "election", ".", "partitionId", ")", ";", "if", "(", "!", "Objects", ".", "equals", "(", "oldTerm", ",", "newTerm", ")", ")", "{", "notifyTermChange", "(", "election", ".", "partitionId", ",", "newTerm", ")", ";", "rebalanced", "=", "true", ";", "}", "}", "}", "}", "}", "// If some elections were rebalanced, reschedule another rebalance after an interval to give the cluster a", "// change to recognize the primary change and replicate state first.", "if", "(", "rebalanced", ")", "{", "scheduleRebalance", "(", ")", ";", "}", "}" ]
Periodically rebalances primaries.
[ "Periodically", "rebalances", "primaries", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/PrimaryElectorService.java#L125-L163
27,631
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java
SnapshotStore.getCurrentSnapshot
public Snapshot getCurrentSnapshot() { Map.Entry<Long, Snapshot> entry = snapshots.lastEntry(); return entry != null ? entry.getValue() : null; }
java
public Snapshot getCurrentSnapshot() { Map.Entry<Long, Snapshot> entry = snapshots.lastEntry(); return entry != null ? entry.getValue() : null; }
[ "public", "Snapshot", "getCurrentSnapshot", "(", ")", "{", "Map", ".", "Entry", "<", "Long", ",", "Snapshot", ">", "entry", "=", "snapshots", ".", "lastEntry", "(", ")", ";", "return", "entry", "!=", "null", "?", "entry", ".", "getValue", "(", ")", ":", "null", ";", "}" ]
Returns the current snapshot. @return the current snapshot
[ "Returns", "the", "current", "snapshot", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java#L96-L99
27,632
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java
SnapshotStore.loadSnapshots
private Collection<Snapshot> loadSnapshots() { // Ensure log directories are created. storage.directory().mkdirs(); List<Snapshot> snapshots = new ArrayList<>(); // Iterate through all files in the log directory. for (File file : storage.directory().listFiles(File::isFile)) { // If the file looks like a segment file, attempt to load the segment. if (SnapshotFile.isSnapshotFile(file)) { SnapshotFile snapshotFile = new SnapshotFile(file); SnapshotDescriptor descriptor = new SnapshotDescriptor(FileBuffer.allocate(file, SnapshotDescriptor.BYTES)); // Valid segments will have been locked. Segments that resulting from failures during log cleaning will be // unlocked and should ultimately be deleted from disk. if (descriptor.isLocked()) { log.debug("Loaded disk snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); snapshots.add(new FileSnapshot(snapshotFile, descriptor, this)); descriptor.close(); } // If the segment descriptor wasn't locked, close and delete the descriptor. else { log.debug("Deleting partial snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); descriptor.close(); descriptor.delete(); } } } return snapshots; }
java
private Collection<Snapshot> loadSnapshots() { // Ensure log directories are created. storage.directory().mkdirs(); List<Snapshot> snapshots = new ArrayList<>(); // Iterate through all files in the log directory. for (File file : storage.directory().listFiles(File::isFile)) { // If the file looks like a segment file, attempt to load the segment. if (SnapshotFile.isSnapshotFile(file)) { SnapshotFile snapshotFile = new SnapshotFile(file); SnapshotDescriptor descriptor = new SnapshotDescriptor(FileBuffer.allocate(file, SnapshotDescriptor.BYTES)); // Valid segments will have been locked. Segments that resulting from failures during log cleaning will be // unlocked and should ultimately be deleted from disk. if (descriptor.isLocked()) { log.debug("Loaded disk snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); snapshots.add(new FileSnapshot(snapshotFile, descriptor, this)); descriptor.close(); } // If the segment descriptor wasn't locked, close and delete the descriptor. else { log.debug("Deleting partial snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); descriptor.close(); descriptor.delete(); } } } return snapshots; }
[ "private", "Collection", "<", "Snapshot", ">", "loadSnapshots", "(", ")", "{", "// Ensure log directories are created.", "storage", ".", "directory", "(", ")", ".", "mkdirs", "(", ")", ";", "List", "<", "Snapshot", ">", "snapshots", "=", "new", "ArrayList", "<>", "(", ")", ";", "// Iterate through all files in the log directory.", "for", "(", "File", "file", ":", "storage", ".", "directory", "(", ")", ".", "listFiles", "(", "File", "::", "isFile", ")", ")", "{", "// If the file looks like a segment file, attempt to load the segment.", "if", "(", "SnapshotFile", ".", "isSnapshotFile", "(", "file", ")", ")", "{", "SnapshotFile", "snapshotFile", "=", "new", "SnapshotFile", "(", "file", ")", ";", "SnapshotDescriptor", "descriptor", "=", "new", "SnapshotDescriptor", "(", "FileBuffer", ".", "allocate", "(", "file", ",", "SnapshotDescriptor", ".", "BYTES", ")", ")", ";", "// Valid segments will have been locked. Segments that resulting from failures during log cleaning will be", "// unlocked and should ultimately be deleted from disk.", "if", "(", "descriptor", ".", "isLocked", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Loaded disk snapshot: {} ({})\"", ",", "descriptor", ".", "index", "(", ")", ",", "snapshotFile", ".", "file", "(", ")", ".", "getName", "(", ")", ")", ";", "snapshots", ".", "add", "(", "new", "FileSnapshot", "(", "snapshotFile", ",", "descriptor", ",", "this", ")", ")", ";", "descriptor", ".", "close", "(", ")", ";", "}", "// If the segment descriptor wasn't locked, close and delete the descriptor.", "else", "{", "log", ".", "debug", "(", "\"Deleting partial snapshot: {} ({})\"", ",", "descriptor", ".", "index", "(", ")", ",", "snapshotFile", ".", "file", "(", ")", ".", "getName", "(", ")", ")", ";", "descriptor", ".", "close", "(", ")", ";", "descriptor", ".", "delete", "(", ")", ";", "}", "}", "}", "return", "snapshots", ";", "}" ]
Loads all available snapshots from disk. @return A list of available snapshots.
[ "Loads", "all", "available", "snapshots", "from", "disk", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java#L116-L147
27,633
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java
SnapshotStore.newTemporarySnapshot
public Snapshot newTemporarySnapshot(long index, WallClockTimestamp timestamp) { SnapshotDescriptor descriptor = SnapshotDescriptor.builder() .withIndex(index) .withTimestamp(timestamp.unixTimestamp()) .build(); return newSnapshot(descriptor, StorageLevel.MEMORY); }
java
public Snapshot newTemporarySnapshot(long index, WallClockTimestamp timestamp) { SnapshotDescriptor descriptor = SnapshotDescriptor.builder() .withIndex(index) .withTimestamp(timestamp.unixTimestamp()) .build(); return newSnapshot(descriptor, StorageLevel.MEMORY); }
[ "public", "Snapshot", "newTemporarySnapshot", "(", "long", "index", ",", "WallClockTimestamp", "timestamp", ")", "{", "SnapshotDescriptor", "descriptor", "=", "SnapshotDescriptor", ".", "builder", "(", ")", ".", "withIndex", "(", "index", ")", ".", "withTimestamp", "(", "timestamp", ".", "unixTimestamp", "(", ")", ")", ".", "build", "(", ")", ";", "return", "newSnapshot", "(", "descriptor", ",", "StorageLevel", ".", "MEMORY", ")", ";", "}" ]
Creates a temporary in-memory snapshot. @param index The snapshot index. @param timestamp The snapshot timestamp. @return The snapshot.
[ "Creates", "a", "temporary", "in", "-", "memory", "snapshot", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java#L156-L162
27,634
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java
RaftPartition.snapshot
public CompletableFuture<Void> snapshot() { RaftPartitionServer server = this.server; if (server != null) { return server.snapshot(); } return CompletableFuture.completedFuture(null); }
java
public CompletableFuture<Void> snapshot() { RaftPartitionServer server = this.server; if (server != null) { return server.snapshot(); } return CompletableFuture.completedFuture(null); }
[ "public", "CompletableFuture", "<", "Void", ">", "snapshot", "(", ")", "{", "RaftPartitionServer", "server", "=", "this", ".", "server", ";", "if", "(", "server", "!=", "null", ")", "{", "return", "server", ".", "snapshot", "(", ")", ";", "}", "return", "CompletableFuture", ".", "completedFuture", "(", "null", ")", ";", "}" ]
Takes a snapshot of the partition. @return a future to be completed once the snapshot is complete
[ "Takes", "a", "snapshot", "of", "the", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java#L115-L121
27,635
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java
RaftPartition.open
CompletableFuture<Partition> open(PartitionMetadata metadata, PartitionManagementService managementService) { this.partition = metadata; this.client = createClient(managementService); if (partition.members().contains(managementService.getMembershipService().getLocalMember().id())) { server = createServer(managementService); return server.start() .thenCompose(v -> client.start()) .thenApply(v -> null); } return client.start() .thenApply(v -> this); }
java
CompletableFuture<Partition> open(PartitionMetadata metadata, PartitionManagementService managementService) { this.partition = metadata; this.client = createClient(managementService); if (partition.members().contains(managementService.getMembershipService().getLocalMember().id())) { server = createServer(managementService); return server.start() .thenCompose(v -> client.start()) .thenApply(v -> null); } return client.start() .thenApply(v -> this); }
[ "CompletableFuture", "<", "Partition", ">", "open", "(", "PartitionMetadata", "metadata", ",", "PartitionManagementService", "managementService", ")", "{", "this", ".", "partition", "=", "metadata", ";", "this", ".", "client", "=", "createClient", "(", "managementService", ")", ";", "if", "(", "partition", ".", "members", "(", ")", ".", "contains", "(", "managementService", ".", "getMembershipService", "(", ")", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ")", ")", "{", "server", "=", "createServer", "(", "managementService", ")", ";", "return", "server", ".", "start", "(", ")", ".", "thenCompose", "(", "v", "->", "client", ".", "start", "(", ")", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}", "return", "client", ".", "start", "(", ")", ".", "thenApply", "(", "v", "->", "this", ")", ";", "}" ]
Opens the partition.
[ "Opens", "the", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java#L131-L142
27,636
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java
RaftPartition.update
CompletableFuture<Void> update(PartitionMetadata metadata, PartitionManagementService managementService) { if (server == null && metadata.members().contains(managementService.getMembershipService().getLocalMember().id())) { server = createServer(managementService); return server.join(metadata.members()); } else if (server != null && !metadata.members().contains(managementService.getMembershipService().getLocalMember().id())) { return server.leave().thenRun(() -> server = null); } return CompletableFuture.completedFuture(null); }
java
CompletableFuture<Void> update(PartitionMetadata metadata, PartitionManagementService managementService) { if (server == null && metadata.members().contains(managementService.getMembershipService().getLocalMember().id())) { server = createServer(managementService); return server.join(metadata.members()); } else if (server != null && !metadata.members().contains(managementService.getMembershipService().getLocalMember().id())) { return server.leave().thenRun(() -> server = null); } return CompletableFuture.completedFuture(null); }
[ "CompletableFuture", "<", "Void", ">", "update", "(", "PartitionMetadata", "metadata", ",", "PartitionManagementService", "managementService", ")", "{", "if", "(", "server", "==", "null", "&&", "metadata", ".", "members", "(", ")", ".", "contains", "(", "managementService", ".", "getMembershipService", "(", ")", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ")", ")", "{", "server", "=", "createServer", "(", "managementService", ")", ";", "return", "server", ".", "join", "(", "metadata", ".", "members", "(", ")", ")", ";", "}", "else", "if", "(", "server", "!=", "null", "&&", "!", "metadata", ".", "members", "(", ")", ".", "contains", "(", "managementService", ".", "getMembershipService", "(", ")", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ")", ")", "{", "return", "server", ".", "leave", "(", ")", ".", "thenRun", "(", "(", ")", "->", "server", "=", "null", ")", ";", "}", "return", "CompletableFuture", ".", "completedFuture", "(", "null", ")", ";", "}" ]
Updates the partition with the given metadata.
[ "Updates", "the", "partition", "with", "the", "given", "metadata", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java#L147-L155
27,637
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java
RaftPartition.close
CompletableFuture<Void> close() { return closeClient() .exceptionally(v -> null) .thenCompose(v -> closeServer()) .exceptionally(v -> null); }
java
CompletableFuture<Void> close() { return closeClient() .exceptionally(v -> null) .thenCompose(v -> closeServer()) .exceptionally(v -> null); }
[ "CompletableFuture", "<", "Void", ">", "close", "(", ")", "{", "return", "closeClient", "(", ")", ".", "exceptionally", "(", "v", "->", "null", ")", ".", "thenCompose", "(", "v", "->", "closeServer", "(", ")", ")", ".", "exceptionally", "(", "v", "->", "null", ")", ";", "}" ]
Closes the partition.
[ "Closes", "the", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java#L160-L165
27,638
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java
RaftPartition.createServer
protected RaftPartitionServer createServer(PartitionManagementService managementService) { return new RaftPartitionServer( this, config, managementService.getMembershipService().getLocalMember().id(), managementService.getMembershipService(), managementService.getMessagingService(), managementService.getPrimitiveTypes(), threadContextFactory); }
java
protected RaftPartitionServer createServer(PartitionManagementService managementService) { return new RaftPartitionServer( this, config, managementService.getMembershipService().getLocalMember().id(), managementService.getMembershipService(), managementService.getMessagingService(), managementService.getPrimitiveTypes(), threadContextFactory); }
[ "protected", "RaftPartitionServer", "createServer", "(", "PartitionManagementService", "managementService", ")", "{", "return", "new", "RaftPartitionServer", "(", "this", ",", "config", ",", "managementService", ".", "getMembershipService", "(", ")", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ",", "managementService", ".", "getMembershipService", "(", ")", ",", "managementService", ".", "getMessagingService", "(", ")", ",", "managementService", ".", "getPrimitiveTypes", "(", ")", ",", "threadContextFactory", ")", ";", "}" ]
Creates a Raft server.
[ "Creates", "a", "Raft", "server", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java#L184-L193
27,639
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java
RaftPartition.createClient
private RaftPartitionClient createClient(PartitionManagementService managementService) { return new RaftPartitionClient( this, managementService.getMembershipService().getLocalMember().id(), new RaftClientCommunicator( name(), Serializer.using(RaftNamespaces.RAFT_PROTOCOL), managementService.getMessagingService()), threadContextFactory); }
java
private RaftPartitionClient createClient(PartitionManagementService managementService) { return new RaftPartitionClient( this, managementService.getMembershipService().getLocalMember().id(), new RaftClientCommunicator( name(), Serializer.using(RaftNamespaces.RAFT_PROTOCOL), managementService.getMessagingService()), threadContextFactory); }
[ "private", "RaftPartitionClient", "createClient", "(", "PartitionManagementService", "managementService", ")", "{", "return", "new", "RaftPartitionClient", "(", "this", ",", "managementService", ".", "getMembershipService", "(", ")", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ",", "new", "RaftClientCommunicator", "(", "name", "(", ")", ",", "Serializer", ".", "using", "(", "RaftNamespaces", ".", "RAFT_PROTOCOL", ")", ",", "managementService", ".", "getMessagingService", "(", ")", ")", ",", "threadContextFactory", ")", ";", "}" ]
Creates a Raft client.
[ "Creates", "a", "Raft", "client", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java#L198-L207
27,640
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java
RaftPartition.delete
public CompletableFuture<Void> delete() { return server.stop().thenCompose(v -> client.stop()).thenRun(() -> { if (server != null) { server.delete(); } }); }
java
public CompletableFuture<Void> delete() { return server.stop().thenCompose(v -> client.stop()).thenRun(() -> { if (server != null) { server.delete(); } }); }
[ "public", "CompletableFuture", "<", "Void", ">", "delete", "(", ")", "{", "return", "server", ".", "stop", "(", ")", ".", "thenCompose", "(", "v", "->", "client", ".", "stop", "(", ")", ")", ".", "thenRun", "(", "(", ")", "->", "{", "if", "(", "server", "!=", "null", ")", "{", "server", ".", "delete", "(", ")", ";", "}", "}", ")", ";", "}" ]
Deletes the partition. @return future to be completed once the partition has been deleted
[ "Deletes", "the", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/partition/RaftPartition.java#L214-L220
27,641
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.setCommandSequence
public void setCommandSequence(long sequence) { // For each increment of the sequence number, trigger query callbacks that are dependent on the specific sequence. for (long i = commandSequence + 1; i <= sequence; i++) { commandSequence = i; List<Runnable> queries = this.sequenceQueries.remove(commandSequence); if (queries != null) { for (Runnable query : queries) { query.run(); } } } }
java
public void setCommandSequence(long sequence) { // For each increment of the sequence number, trigger query callbacks that are dependent on the specific sequence. for (long i = commandSequence + 1; i <= sequence; i++) { commandSequence = i; List<Runnable> queries = this.sequenceQueries.remove(commandSequence); if (queries != null) { for (Runnable query : queries) { query.run(); } } } }
[ "public", "void", "setCommandSequence", "(", "long", "sequence", ")", "{", "// For each increment of the sequence number, trigger query callbacks that are dependent on the specific sequence.", "for", "(", "long", "i", "=", "commandSequence", "+", "1", ";", "i", "<=", "sequence", ";", "i", "++", ")", "{", "commandSequence", "=", "i", ";", "List", "<", "Runnable", ">", "queries", "=", "this", ".", "sequenceQueries", ".", "remove", "(", "commandSequence", ")", ";", "if", "(", "queries", "!=", "null", ")", "{", "for", "(", "Runnable", "query", ":", "queries", ")", "{", "query", ".", "run", "(", ")", ";", "}", "}", "}", "}" ]
Sets the session operation sequence number. @param sequence The session operation sequence number.
[ "Sets", "the", "session", "operation", "sequence", "number", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L257-L268
27,642
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.setLastApplied
public void setLastApplied(long index) { // Query callbacks for this session are added to the indexQueries map to be executed once the required index // for the query is reached. For each increment of the index, trigger query callbacks that are dependent // on the specific index. for (long i = lastApplied + 1; i <= index; i++) { lastApplied = i; List<Runnable> queries = this.indexQueries.remove(lastApplied); if (queries != null) { for (Runnable query : queries) { query.run(); } } } }
java
public void setLastApplied(long index) { // Query callbacks for this session are added to the indexQueries map to be executed once the required index // for the query is reached. For each increment of the index, trigger query callbacks that are dependent // on the specific index. for (long i = lastApplied + 1; i <= index; i++) { lastApplied = i; List<Runnable> queries = this.indexQueries.remove(lastApplied); if (queries != null) { for (Runnable query : queries) { query.run(); } } } }
[ "public", "void", "setLastApplied", "(", "long", "index", ")", "{", "// Query callbacks for this session are added to the indexQueries map to be executed once the required index", "// for the query is reached. For each increment of the index, trigger query callbacks that are dependent", "// on the specific index.", "for", "(", "long", "i", "=", "lastApplied", "+", "1", ";", "i", "<=", "index", ";", "i", "++", ")", "{", "lastApplied", "=", "i", ";", "List", "<", "Runnable", ">", "queries", "=", "this", ".", "indexQueries", ".", "remove", "(", "lastApplied", ")", ";", "if", "(", "queries", "!=", "null", ")", "{", "for", "(", "Runnable", "query", ":", "queries", ")", "{", "query", ".", "run", "(", ")", ";", "}", "}", "}", "}" ]
Sets the session index. @param index The session index.
[ "Sets", "the", "session", "index", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L284-L297
27,643
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.registerSequenceQuery
public void registerSequenceQuery(long sequence, Runnable query) { // Add a query to be run once the session's sequence number reaches the given sequence number. List<Runnable> queries = this.sequenceQueries.computeIfAbsent(sequence, v -> new LinkedList<Runnable>()); queries.add(query); }
java
public void registerSequenceQuery(long sequence, Runnable query) { // Add a query to be run once the session's sequence number reaches the given sequence number. List<Runnable> queries = this.sequenceQueries.computeIfAbsent(sequence, v -> new LinkedList<Runnable>()); queries.add(query); }
[ "public", "void", "registerSequenceQuery", "(", "long", "sequence", ",", "Runnable", "query", ")", "{", "// Add a query to be run once the session's sequence number reaches the given sequence number.", "List", "<", "Runnable", ">", "queries", "=", "this", ".", "sequenceQueries", ".", "computeIfAbsent", "(", "sequence", ",", "v", "->", "new", "LinkedList", "<", "Runnable", ">", "(", ")", ")", ";", "queries", ".", "add", "(", "query", ")", ";", "}" ]
Registers a causal session query. @param sequence The session sequence number at which to execute the query. @param query The query to execute.
[ "Registers", "a", "causal", "session", "query", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L305-L309
27,644
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.registerIndexQuery
public void registerIndexQuery(long index, Runnable query) { // Add a query to be run once the session's index reaches the given index. List<Runnable> queries = this.indexQueries.computeIfAbsent(index, v -> new LinkedList<>()); queries.add(query); }
java
public void registerIndexQuery(long index, Runnable query) { // Add a query to be run once the session's index reaches the given index. List<Runnable> queries = this.indexQueries.computeIfAbsent(index, v -> new LinkedList<>()); queries.add(query); }
[ "public", "void", "registerIndexQuery", "(", "long", "index", ",", "Runnable", "query", ")", "{", "// Add a query to be run once the session's index reaches the given index.", "List", "<", "Runnable", ">", "queries", "=", "this", ".", "indexQueries", ".", "computeIfAbsent", "(", "index", ",", "v", "->", "new", "LinkedList", "<>", "(", ")", ")", ";", "queries", ".", "add", "(", "query", ")", ";", "}" ]
Registers a session index query. @param index The state machine index at which to execute the query. @param query The query to execute.
[ "Registers", "a", "session", "index", "query", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L317-L321
27,645
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.clearCommands
public Collection<PendingCommand> clearCommands() { Collection<PendingCommand> commands = Lists.newArrayList(pendingCommands.values()); pendingCommands.clear(); return commands; }
java
public Collection<PendingCommand> clearCommands() { Collection<PendingCommand> commands = Lists.newArrayList(pendingCommands.values()); pendingCommands.clear(); return commands; }
[ "public", "Collection", "<", "PendingCommand", ">", "clearCommands", "(", ")", "{", "Collection", "<", "PendingCommand", ">", "commands", "=", "Lists", ".", "newArrayList", "(", "pendingCommands", ".", "values", "(", ")", ")", ";", "pendingCommands", ".", "clear", "(", ")", ";", "return", "commands", ";", "}" ]
Clears and returns all pending commands. @return a collection of pending commands
[ "Clears", "and", "returns", "all", "pending", "commands", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L367-L371
27,646
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.getLastCompleted
public long getLastCompleted() { // If there are any queued events, return the index prior to the first event in the queue. EventHolder event = events.peek(); if (event != null && event.eventIndex > completeIndex) { return event.eventIndex - 1; } // If no events are queued, return the highest index applied to the session. return lastApplied; }
java
public long getLastCompleted() { // If there are any queued events, return the index prior to the first event in the queue. EventHolder event = events.peek(); if (event != null && event.eventIndex > completeIndex) { return event.eventIndex - 1; } // If no events are queued, return the highest index applied to the session. return lastApplied; }
[ "public", "long", "getLastCompleted", "(", ")", "{", "// If there are any queued events, return the index prior to the first event in the queue.", "EventHolder", "event", "=", "events", ".", "peek", "(", ")", ";", "if", "(", "event", "!=", "null", "&&", "event", ".", "eventIndex", ">", "completeIndex", ")", "{", "return", "event", ".", "eventIndex", "-", "1", ";", "}", "// If no events are queued, return the highest index applied to the session.", "return", "lastApplied", ";", "}" ]
Returns the index of the highest event acked for the session. @return The index of the highest event acked for the session.
[ "Returns", "the", "index", "of", "the", "highest", "event", "acked", "for", "the", "session", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L481-L489
27,647
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.clearEvents
private void clearEvents(long index) { if (index > completeIndex) { EventHolder event = events.peek(); while (event != null && event.eventIndex <= index) { events.remove(); completeIndex = event.eventIndex; event = events.peek(); } completeIndex = index; } }
java
private void clearEvents(long index) { if (index > completeIndex) { EventHolder event = events.peek(); while (event != null && event.eventIndex <= index) { events.remove(); completeIndex = event.eventIndex; event = events.peek(); } completeIndex = index; } }
[ "private", "void", "clearEvents", "(", "long", "index", ")", "{", "if", "(", "index", ">", "completeIndex", ")", "{", "EventHolder", "event", "=", "events", ".", "peek", "(", ")", ";", "while", "(", "event", "!=", "null", "&&", "event", ".", "eventIndex", "<=", "index", ")", "{", "events", ".", "remove", "(", ")", ";", "completeIndex", "=", "event", ".", "eventIndex", ";", "event", "=", "events", ".", "peek", "(", ")", ";", "}", "completeIndex", "=", "index", ";", "}", "}" ]
Clears events up to the given sequence. @param index The index to clear.
[ "Clears", "events", "up", "to", "the", "given", "sequence", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L505-L515
27,648
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.sendEvents
private void sendEvents(EventHolder event) { // Only send events to the client if this server is the leader. if (server.isLeader()) { eventExecutor.execute(() -> { PublishRequest request = PublishRequest.builder() .withSession(sessionId().id()) .withEventIndex(event.eventIndex) .withPreviousIndex(event.previousIndex) .withEvents(event.events) .build(); log.trace("Sending {}", request); protocol.publish(memberId(), request); }); } }
java
private void sendEvents(EventHolder event) { // Only send events to the client if this server is the leader. if (server.isLeader()) { eventExecutor.execute(() -> { PublishRequest request = PublishRequest.builder() .withSession(sessionId().id()) .withEventIndex(event.eventIndex) .withPreviousIndex(event.previousIndex) .withEvents(event.events) .build(); log.trace("Sending {}", request); protocol.publish(memberId(), request); }); } }
[ "private", "void", "sendEvents", "(", "EventHolder", "event", ")", "{", "// Only send events to the client if this server is the leader.", "if", "(", "server", ".", "isLeader", "(", ")", ")", "{", "eventExecutor", ".", "execute", "(", "(", ")", "->", "{", "PublishRequest", "request", "=", "PublishRequest", ".", "builder", "(", ")", ".", "withSession", "(", "sessionId", "(", ")", ".", "id", "(", ")", ")", ".", "withEventIndex", "(", "event", ".", "eventIndex", ")", ".", "withPreviousIndex", "(", "event", ".", "previousIndex", ")", ".", "withEvents", "(", "event", ".", "events", ")", ".", "build", "(", ")", ";", "log", ".", "trace", "(", "\"Sending {}\"", ",", "request", ")", ";", "protocol", ".", "publish", "(", "memberId", "(", ")", ",", "request", ")", ";", "}", ")", ";", "}", "}" ]
Sends an event to the session.
[ "Sends", "an", "event", "to", "the", "session", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L532-L547
27,649
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java
RaftSession.open
public void open() { setState(State.OPEN); protocol.registerResetListener(sessionId(), request -> resendEvents(request.index()), server.getServiceManager().executor()); }
java
public void open() { setState(State.OPEN); protocol.registerResetListener(sessionId(), request -> resendEvents(request.index()), server.getServiceManager().executor()); }
[ "public", "void", "open", "(", ")", "{", "setState", "(", "State", ".", "OPEN", ")", ";", "protocol", ".", "registerResetListener", "(", "sessionId", "(", ")", ",", "request", "->", "resendEvents", "(", "request", ".", "index", "(", ")", ")", ",", "server", ".", "getServiceManager", "(", ")", ".", "executor", "(", ")", ")", ";", "}" ]
Opens the session.
[ "Opens", "the", "session", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/RaftSession.java#L552-L555
27,650
atomix/atomix
primitive/src/main/java/io/atomix/primitive/proxy/impl/AbstractProxyClient.java
AbstractProxyClient.onStateChange
private synchronized void onStateChange(PartitionId partitionId, PrimitiveState state) { states.put(partitionId, state); switch (state) { case CONNECTED: if (this.state != PrimitiveState.CONNECTED && !states.containsValue(PrimitiveState.SUSPENDED) && !states.containsValue(PrimitiveState.CLOSED)) { this.state = PrimitiveState.CONNECTED; stateChangeListeners.forEach(l -> l.accept(PrimitiveState.CONNECTED)); } break; case SUSPENDED: if (this.state == PrimitiveState.CONNECTED) { this.state = PrimitiveState.SUSPENDED; stateChangeListeners.forEach(l -> l.accept(PrimitiveState.SUSPENDED)); } break; case CLOSED: if (this.state != PrimitiveState.CLOSED) { this.state = PrimitiveState.CLOSED; stateChangeListeners.forEach(l -> l.accept(PrimitiveState.CLOSED)); } break; } }
java
private synchronized void onStateChange(PartitionId partitionId, PrimitiveState state) { states.put(partitionId, state); switch (state) { case CONNECTED: if (this.state != PrimitiveState.CONNECTED && !states.containsValue(PrimitiveState.SUSPENDED) && !states.containsValue(PrimitiveState.CLOSED)) { this.state = PrimitiveState.CONNECTED; stateChangeListeners.forEach(l -> l.accept(PrimitiveState.CONNECTED)); } break; case SUSPENDED: if (this.state == PrimitiveState.CONNECTED) { this.state = PrimitiveState.SUSPENDED; stateChangeListeners.forEach(l -> l.accept(PrimitiveState.SUSPENDED)); } break; case CLOSED: if (this.state != PrimitiveState.CLOSED) { this.state = PrimitiveState.CLOSED; stateChangeListeners.forEach(l -> l.accept(PrimitiveState.CLOSED)); } break; } }
[ "private", "synchronized", "void", "onStateChange", "(", "PartitionId", "partitionId", ",", "PrimitiveState", "state", ")", "{", "states", ".", "put", "(", "partitionId", ",", "state", ")", ";", "switch", "(", "state", ")", "{", "case", "CONNECTED", ":", "if", "(", "this", ".", "state", "!=", "PrimitiveState", ".", "CONNECTED", "&&", "!", "states", ".", "containsValue", "(", "PrimitiveState", ".", "SUSPENDED", ")", "&&", "!", "states", ".", "containsValue", "(", "PrimitiveState", ".", "CLOSED", ")", ")", "{", "this", ".", "state", "=", "PrimitiveState", ".", "CONNECTED", ";", "stateChangeListeners", ".", "forEach", "(", "l", "->", "l", ".", "accept", "(", "PrimitiveState", ".", "CONNECTED", ")", ")", ";", "}", "break", ";", "case", "SUSPENDED", ":", "if", "(", "this", ".", "state", "==", "PrimitiveState", ".", "CONNECTED", ")", "{", "this", ".", "state", "=", "PrimitiveState", ".", "SUSPENDED", ";", "stateChangeListeners", ".", "forEach", "(", "l", "->", "l", ".", "accept", "(", "PrimitiveState", ".", "SUSPENDED", ")", ")", ";", "}", "break", ";", "case", "CLOSED", ":", "if", "(", "this", ".", "state", "!=", "PrimitiveState", ".", "CLOSED", ")", "{", "this", ".", "state", "=", "PrimitiveState", ".", "CLOSED", ";", "stateChangeListeners", ".", "forEach", "(", "l", "->", "l", ".", "accept", "(", "PrimitiveState", ".", "CLOSED", ")", ")", ";", "}", "break", ";", "}", "}" ]
Handles a partition proxy state change.
[ "Handles", "a", "partition", "proxy", "state", "change", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/proxy/impl/AbstractProxyClient.java#L148-L170
27,651
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/MapValue.java
MapValue.isNewerThan
public boolean isNewerThan(MapValue other) { if (other == null) { return true; } return this.timestamp.isNewerThan(other.timestamp); }
java
public boolean isNewerThan(MapValue other) { if (other == null) { return true; } return this.timestamp.isNewerThan(other.timestamp); }
[ "public", "boolean", "isNewerThan", "(", "MapValue", "other", ")", "{", "if", "(", "other", "==", "null", ")", "{", "return", "true", ";", "}", "return", "this", ".", "timestamp", ".", "isNewerThan", "(", "other", ".", "timestamp", ")", ";", "}" ]
Tests if this value is newer than the specified MapValue. @param other the value to be compared @return true if this value is newer than other
[ "Tests", "if", "this", "value", "is", "newer", "than", "the", "specified", "MapValue", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/MapValue.java#L139-L144
27,652
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/OrderedFuture.java
OrderedFuture.orderedFuture
private CompletableFuture<T> orderedFuture() { if (!complete) { synchronized (orderedFutures) { if (!complete) { CompletableFuture<T> future = new CompletableFuture<>(); orderedFutures.add(future); return future; } } } // Completed if (error == null) { return CompletableFuture.completedFuture(result); } else { return Futures.exceptionalFuture(error); } }
java
private CompletableFuture<T> orderedFuture() { if (!complete) { synchronized (orderedFutures) { if (!complete) { CompletableFuture<T> future = new CompletableFuture<>(); orderedFutures.add(future); return future; } } } // Completed if (error == null) { return CompletableFuture.completedFuture(result); } else { return Futures.exceptionalFuture(error); } }
[ "private", "CompletableFuture", "<", "T", ">", "orderedFuture", "(", ")", "{", "if", "(", "!", "complete", ")", "{", "synchronized", "(", "orderedFutures", ")", "{", "if", "(", "!", "complete", ")", "{", "CompletableFuture", "<", "T", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "orderedFutures", ".", "add", "(", "future", ")", ";", "return", "future", ";", "}", "}", "}", "// Completed", "if", "(", "error", "==", "null", ")", "{", "return", "CompletableFuture", ".", "completedFuture", "(", "result", ")", ";", "}", "else", "{", "return", "Futures", ".", "exceptionalFuture", "(", "error", ")", ";", "}", "}" ]
Adds a new ordered future.
[ "Adds", "a", "new", "ordered", "future", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/OrderedFuture.java#L110-L127
27,653
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/OrderedFuture.java
OrderedFuture.complete
private void complete(T result, Throwable error) { synchronized (orderedFutures) { this.result = result; this.error = error; this.complete = true; if (error == null) { for (CompletableFuture<T> future : orderedFutures) { future.complete(result); } } else { for (CompletableFuture<T> future : orderedFutures) { future.completeExceptionally(error); } } orderedFutures.clear(); } }
java
private void complete(T result, Throwable error) { synchronized (orderedFutures) { this.result = result; this.error = error; this.complete = true; if (error == null) { for (CompletableFuture<T> future : orderedFutures) { future.complete(result); } } else { for (CompletableFuture<T> future : orderedFutures) { future.completeExceptionally(error); } } orderedFutures.clear(); } }
[ "private", "void", "complete", "(", "T", "result", ",", "Throwable", "error", ")", "{", "synchronized", "(", "orderedFutures", ")", "{", "this", ".", "result", "=", "result", ";", "this", ".", "error", "=", "error", ";", "this", ".", "complete", "=", "true", ";", "if", "(", "error", "==", "null", ")", "{", "for", "(", "CompletableFuture", "<", "T", ">", "future", ":", "orderedFutures", ")", "{", "future", ".", "complete", "(", "result", ")", ";", "}", "}", "else", "{", "for", "(", "CompletableFuture", "<", "T", ">", "future", ":", "orderedFutures", ")", "{", "future", ".", "completeExceptionally", "(", "error", ")", ";", "}", "}", "orderedFutures", ".", "clear", "(", ")", ";", "}", "}" ]
Completes futures in FIFO order.
[ "Completes", "futures", "in", "FIFO", "order", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/OrderedFuture.java#L132-L148
27,654
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionInvoker.java
RaftSessionInvoker.invoke
public CompletableFuture<byte[]> invoke(PrimitiveOperation operation) { CompletableFuture<byte[]> future = new CompletableFuture<>(); switch (operation.id().type()) { case COMMAND: context.execute(() -> invokeCommand(operation, future)); break; case QUERY: context.execute(() -> invokeQuery(operation, future)); break; default: throw new IllegalArgumentException("Unknown operation type " + operation.id().type()); } return future; }
java
public CompletableFuture<byte[]> invoke(PrimitiveOperation operation) { CompletableFuture<byte[]> future = new CompletableFuture<>(); switch (operation.id().type()) { case COMMAND: context.execute(() -> invokeCommand(operation, future)); break; case QUERY: context.execute(() -> invokeQuery(operation, future)); break; default: throw new IllegalArgumentException("Unknown operation type " + operation.id().type()); } return future; }
[ "public", "CompletableFuture", "<", "byte", "[", "]", ">", "invoke", "(", "PrimitiveOperation", "operation", ")", "{", "CompletableFuture", "<", "byte", "[", "]", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "switch", "(", "operation", ".", "id", "(", ")", ".", "type", "(", ")", ")", "{", "case", "COMMAND", ":", "context", ".", "execute", "(", "(", ")", "->", "invokeCommand", "(", "operation", ",", "future", ")", ")", ";", "break", ";", "case", "QUERY", ":", "context", ".", "execute", "(", "(", ")", "->", "invokeQuery", "(", "operation", ",", "future", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Unknown operation type \"", "+", "operation", ".", "id", "(", ")", ".", "type", "(", ")", ")", ";", "}", "return", "future", ";", "}" ]
Submits a operation to the cluster. @param operation The operation to submit. @return A completable future to be completed once the command has been submitted.
[ "Submits", "a", "operation", "to", "the", "cluster", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionInvoker.java#L93-L106
27,655
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/MemberSelectorManager.java
MemberSelectorManager.createSelector
public MemberSelector createSelector(CommunicationStrategy selectionStrategy) { MemberSelector selector = new MemberSelector(leader, members, selectionStrategy, this); selectors.add(selector); return selector; }
java
public MemberSelector createSelector(CommunicationStrategy selectionStrategy) { MemberSelector selector = new MemberSelector(leader, members, selectionStrategy, this); selectors.add(selector); return selector; }
[ "public", "MemberSelector", "createSelector", "(", "CommunicationStrategy", "selectionStrategy", ")", "{", "MemberSelector", "selector", "=", "new", "MemberSelector", "(", "leader", ",", "members", ",", "selectionStrategy", ",", "this", ")", ";", "selectors", ".", "add", "(", "selector", ")", ";", "return", "selector", ";", "}" ]
Creates a new address selector. @param selectionStrategy The server selection strategy. @return A new address selector.
[ "Creates", "a", "new", "address", "selector", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/MemberSelectorManager.java#L80-L84
27,656
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/MemberSelectorManager.java
MemberSelectorManager.resetAll
public void resetAll(MemberId leader, Collection<MemberId> members) { MemberId oldLeader = this.leader; this.leader = leader; this.members = Lists.newLinkedList(members); selectors.forEach(s -> s.reset(leader, this.members)); if (!Objects.equals(oldLeader, leader)) { leaderChangeListeners.forEach(l -> l.accept(leader)); } }
java
public void resetAll(MemberId leader, Collection<MemberId> members) { MemberId oldLeader = this.leader; this.leader = leader; this.members = Lists.newLinkedList(members); selectors.forEach(s -> s.reset(leader, this.members)); if (!Objects.equals(oldLeader, leader)) { leaderChangeListeners.forEach(l -> l.accept(leader)); } }
[ "public", "void", "resetAll", "(", "MemberId", "leader", ",", "Collection", "<", "MemberId", ">", "members", ")", "{", "MemberId", "oldLeader", "=", "this", ".", "leader", ";", "this", ".", "leader", "=", "leader", ";", "this", ".", "members", "=", "Lists", ".", "newLinkedList", "(", "members", ")", ";", "selectors", ".", "forEach", "(", "s", "->", "s", ".", "reset", "(", "leader", ",", "this", ".", "members", ")", ")", ";", "if", "(", "!", "Objects", ".", "equals", "(", "oldLeader", ",", "leader", ")", ")", "{", "leaderChangeListeners", ".", "forEach", "(", "l", "->", "l", ".", "accept", "(", "leader", ")", ")", ";", "}", "}" ]
Resets all child selectors. @param leader The current cluster leader. @param members The collection of all active members.
[ "Resets", "all", "child", "selectors", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/MemberSelectorManager.java#L99-L107
27,657
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/AtomixFuture.java
AtomixFuture.wrap
public static <T> AtomixFuture<T> wrap(CompletableFuture<T> future) { AtomixFuture<T> newFuture = new AtomixFuture<>(); future.whenComplete((result, error) -> { if (error == null) { newFuture.complete(result); } else { newFuture.completeExceptionally(error); } }); return newFuture; }
java
public static <T> AtomixFuture<T> wrap(CompletableFuture<T> future) { AtomixFuture<T> newFuture = new AtomixFuture<>(); future.whenComplete((result, error) -> { if (error == null) { newFuture.complete(result); } else { newFuture.completeExceptionally(error); } }); return newFuture; }
[ "public", "static", "<", "T", ">", "AtomixFuture", "<", "T", ">", "wrap", "(", "CompletableFuture", "<", "T", ">", "future", ")", "{", "AtomixFuture", "<", "T", ">", "newFuture", "=", "new", "AtomixFuture", "<>", "(", ")", ";", "future", ".", "whenComplete", "(", "(", "result", ",", "error", ")", "->", "{", "if", "(", "error", "==", "null", ")", "{", "newFuture", ".", "complete", "(", "result", ")", ";", "}", "else", "{", "newFuture", ".", "completeExceptionally", "(", "error", ")", ";", "}", "}", ")", ";", "return", "newFuture", ";", "}" ]
Wraps the given future in a new blockable future. @param future the future to wrap @param <T> the future value type @return a new blockable future
[ "Wraps", "the", "given", "future", "in", "a", "new", "blockable", "future", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/AtomixFuture.java#L42-L52
27,658
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/AtomixFuture.java
AtomixFuture.completedFuture
public static <T> CompletableFuture<T> completedFuture(T result) { CompletableFuture<T> future = new AtomixFuture<>(); future.complete(result); return future; }
java
public static <T> CompletableFuture<T> completedFuture(T result) { CompletableFuture<T> future = new AtomixFuture<>(); future.complete(result); return future; }
[ "public", "static", "<", "T", ">", "CompletableFuture", "<", "T", ">", "completedFuture", "(", "T", "result", ")", "{", "CompletableFuture", "<", "T", ">", "future", "=", "new", "AtomixFuture", "<>", "(", ")", ";", "future", ".", "complete", "(", "result", ")", ";", "return", "future", ";", "}" ]
Returns a new completed Atomix future. @param result the future result @param <T> the future result type @return the completed future
[ "Returns", "a", "new", "completed", "Atomix", "future", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/AtomixFuture.java#L61-L65
27,659
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/AtomixFuture.java
AtomixFuture.exceptionalFuture
public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) { CompletableFuture<T> future = new AtomixFuture<>(); future.completeExceptionally(t); return future; }
java
public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) { CompletableFuture<T> future = new AtomixFuture<>(); future.completeExceptionally(t); return future; }
[ "public", "static", "<", "T", ">", "CompletableFuture", "<", "T", ">", "exceptionalFuture", "(", "Throwable", "t", ")", "{", "CompletableFuture", "<", "T", ">", "future", "=", "new", "AtomixFuture", "<>", "(", ")", ";", "future", ".", "completeExceptionally", "(", "t", ")", ";", "return", "future", ";", "}" ]
Returns a new exceptionally completed Atomix future. @param t the future exception @param <T> the future result type @return the completed future
[ "Returns", "a", "new", "exceptionally", "completed", "Atomix", "future", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/AtomixFuture.java#L74-L78
27,660
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/ReferencePool.java
ReferencePool.acquire
public T acquire() { if (closed) { throw new IllegalStateException("pool closed"); } T reference = pool.poll(); if (reference == null) { reference = factory.createReference(this); } reference.acquire(); return reference; }
java
public T acquire() { if (closed) { throw new IllegalStateException("pool closed"); } T reference = pool.poll(); if (reference == null) { reference = factory.createReference(this); } reference.acquire(); return reference; }
[ "public", "T", "acquire", "(", ")", "{", "if", "(", "closed", ")", "{", "throw", "new", "IllegalStateException", "(", "\"pool closed\"", ")", ";", "}", "T", "reference", "=", "pool", ".", "poll", "(", ")", ";", "if", "(", "reference", "==", "null", ")", "{", "reference", "=", "factory", ".", "createReference", "(", "this", ")", ";", "}", "reference", ".", "acquire", "(", ")", ";", "return", "reference", ";", "}" ]
Acquires a reference. @return The acquired reference.
[ "Acquires", "a", "reference", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/ReferencePool.java#L43-L54
27,661
atomix/atomix
protocols/log/src/main/java/io/atomix/protocols/log/DistributedLogSessionClient.java
DistributedLogSessionClient.sessionBuilder
public LogSession.Builder sessionBuilder() { return new DistributedLogSession.Builder() { @Override public LogSession build() { return new DistributedLogSession( partitionId, sessionIdProvider.get().join(), clusterMembershipService, protocol, primaryElection, threadContextFactory.createContext()); } }; }
java
public LogSession.Builder sessionBuilder() { return new DistributedLogSession.Builder() { @Override public LogSession build() { return new DistributedLogSession( partitionId, sessionIdProvider.get().join(), clusterMembershipService, protocol, primaryElection, threadContextFactory.createContext()); } }; }
[ "public", "LogSession", ".", "Builder", "sessionBuilder", "(", ")", "{", "return", "new", "DistributedLogSession", ".", "Builder", "(", ")", "{", "@", "Override", "public", "LogSession", "build", "(", ")", "{", "return", "new", "DistributedLogSession", "(", "partitionId", ",", "sessionIdProvider", ".", "get", "(", ")", ".", "join", "(", ")", ",", "clusterMembershipService", ",", "protocol", ",", "primaryElection", ",", "threadContextFactory", ".", "createContext", "(", ")", ")", ";", "}", "}", ";", "}" ]
Returns a new distributed log session builder. @return a new distributed log session builder
[ "Returns", "a", "new", "distributed", "log", "session", "builder", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/log/src/main/java/io/atomix/protocols/log/DistributedLogSessionClient.java#L87-L100
27,662
atomix/atomix
storage/src/main/java/io/atomix/storage/buffer/AbstractBuffer.java
AbstractBuffer.checkRead
protected int checkRead(int length) { checkRead(position, length); int previousPosition = this.position; this.position = previousPosition + length; return offset(previousPosition); }
java
protected int checkRead(int length) { checkRead(position, length); int previousPosition = this.position; this.position = previousPosition + length; return offset(previousPosition); }
[ "protected", "int", "checkRead", "(", "int", "length", ")", "{", "checkRead", "(", "position", ",", "length", ")", ";", "int", "previousPosition", "=", "this", ".", "position", ";", "this", ".", "position", "=", "previousPosition", "+", "length", ";", "return", "offset", "(", "previousPosition", ")", ";", "}" ]
Checks bounds for a read for the given length.
[ "Checks", "bounds", "for", "a", "read", "for", "the", "given", "length", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/buffer/AbstractBuffer.java#L371-L376
27,663
atomix/atomix
storage/src/main/java/io/atomix/storage/buffer/AbstractBuffer.java
AbstractBuffer.checkWrite
protected int checkWrite(int length) { checkWrite(position, length); int previousPosition = this.position; this.position = previousPosition + length; return offset(previousPosition); }
java
protected int checkWrite(int length) { checkWrite(position, length); int previousPosition = this.position; this.position = previousPosition + length; return offset(previousPosition); }
[ "protected", "int", "checkWrite", "(", "int", "length", ")", "{", "checkWrite", "(", "position", ",", "length", ")", ";", "int", "previousPosition", "=", "this", ".", "position", ";", "this", ".", "position", "=", "previousPosition", "+", "length", ";", "return", "offset", "(", "previousPosition", ")", ";", "}" ]
Checks bounds for a write of the given length.
[ "Checks", "bounds", "for", "a", "write", "of", "the", "given", "length", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/buffer/AbstractBuffer.java#L406-L411
27,664
atomix/atomix
storage/src/main/java/io/atomix/storage/buffer/AbstractBuffer.java
AbstractBuffer.calculateCapacity
private int calculateCapacity(int minimumCapacity) { int newCapacity = Math.min(Math.max(capacity, 2), minimumCapacity); while (newCapacity < Math.min(minimumCapacity, maxCapacity)) { newCapacity <<= 1; } return Math.min(newCapacity, maxCapacity); }
java
private int calculateCapacity(int minimumCapacity) { int newCapacity = Math.min(Math.max(capacity, 2), minimumCapacity); while (newCapacity < Math.min(minimumCapacity, maxCapacity)) { newCapacity <<= 1; } return Math.min(newCapacity, maxCapacity); }
[ "private", "int", "calculateCapacity", "(", "int", "minimumCapacity", ")", "{", "int", "newCapacity", "=", "Math", ".", "min", "(", "Math", ".", "max", "(", "capacity", ",", "2", ")", ",", "minimumCapacity", ")", ";", "while", "(", "newCapacity", "<", "Math", ".", "min", "(", "minimumCapacity", ",", "maxCapacity", ")", ")", "{", "newCapacity", "<<=", "1", ";", "}", "return", "Math", ".", "min", "(", "newCapacity", ",", "maxCapacity", ")", ";", "}" ]
Calculates the next capacity that meets the given minimum capacity.
[ "Calculates", "the", "next", "capacity", "that", "meets", "the", "given", "minimum", "capacity", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/buffer/AbstractBuffer.java#L437-L443
27,665
atomix/atomix
primitive/src/main/java/io/atomix/primitive/AbstractAsyncPrimitive.java
AbstractAsyncPrimitive.connect
@SuppressWarnings("unchecked") public CompletableFuture<A> connect() { return registry.createPrimitive(name(), type()) .thenApply(v -> (A) this); }
java
@SuppressWarnings("unchecked") public CompletableFuture<A> connect() { return registry.createPrimitive(name(), type()) .thenApply(v -> (A) this); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "CompletableFuture", "<", "A", ">", "connect", "(", ")", "{", "return", "registry", ".", "createPrimitive", "(", "name", "(", ")", ",", "type", "(", ")", ")", ".", "thenApply", "(", "v", "->", "(", "A", ")", "this", ")", ";", "}" ]
Connects the primitive. @return a future to be completed once the primitive has been connected
[ "Connects", "the", "primitive", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/AbstractAsyncPrimitive.java#L79-L83
27,666
atomix/atomix
cluster/src/main/java/io/atomix/cluster/MemberConfig.java
MemberConfig.setProperties
public MemberConfig setProperties(Map<String, String> map) { Properties properties = new Properties(); properties.putAll(map); return setProperties(properties); }
java
public MemberConfig setProperties(Map<String, String> map) { Properties properties = new Properties(); properties.putAll(map); return setProperties(properties); }
[ "public", "MemberConfig", "setProperties", "(", "Map", "<", "String", ",", "String", ">", "map", ")", "{", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "properties", ".", "putAll", "(", "map", ")", ";", "return", "setProperties", "(", "properties", ")", ";", "}" ]
Sets the member properties. @param map the member properties @return the member configuration
[ "Sets", "the", "member", "properties", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/MemberConfig.java#L188-L192
27,667
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/FileChannelJournalSegmentWriter.java
FileChannelJournalSegmentWriter.isFull
public boolean isFull() { return size() >= segment.descriptor().maxSegmentSize() || getNextIndex() - firstIndex >= segment.descriptor().maxEntries(); }
java
public boolean isFull() { return size() >= segment.descriptor().maxSegmentSize() || getNextIndex() - firstIndex >= segment.descriptor().maxEntries(); }
[ "public", "boolean", "isFull", "(", ")", "{", "return", "size", "(", ")", ">=", "segment", ".", "descriptor", "(", ")", ".", "maxSegmentSize", "(", ")", "||", "getNextIndex", "(", ")", "-", "firstIndex", ">=", "segment", ".", "descriptor", "(", ")", ".", "maxEntries", "(", ")", ";", "}" ]
Returns a boolean indicating whether the segment is full. @return Indicates whether the segment is full.
[ "Returns", "a", "boolean", "indicating", "whether", "the", "segment", "is", "full", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/FileChannelJournalSegmentWriter.java#L195-L198
27,668
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/FileChannelJournalSegmentWriter.java
FileChannelJournalSegmentWriter.zero
private ByteBuffer zero() { memory.clear(); for (int i = 0; i < memory.limit(); i++) { memory.put(i, (byte) 0); } return memory; }
java
private ByteBuffer zero() { memory.clear(); for (int i = 0; i < memory.limit(); i++) { memory.put(i, (byte) 0); } return memory; }
[ "private", "ByteBuffer", "zero", "(", ")", "{", "memory", ".", "clear", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "memory", ".", "limit", "(", ")", ";", "i", "++", ")", "{", "memory", ".", "put", "(", "i", ",", "(", "byte", ")", "0", ")", ";", "}", "return", "memory", ";", "}" ]
Returns a zeroed out byte buffer.
[ "Returns", "a", "zeroed", "out", "byte", "buffer", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/FileChannelJournalSegmentWriter.java#L315-L321
27,669
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/AntiEntropyMapDelegate.java
AntiEntropyMapDelegate.bootstrap
private void bootstrap() { List<MemberId> activePeers = bootstrapPeersSupplier.get(); if (activePeers.isEmpty()) { return; } try { requestBootstrapFromPeers(activePeers) .get(DistributedPrimitive.DEFAULT_OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { LOGGER.debug("Failed to bootstrap ec map {}: {}", mapName, ExceptionUtils.getStackTrace(e)); } }
java
private void bootstrap() { List<MemberId> activePeers = bootstrapPeersSupplier.get(); if (activePeers.isEmpty()) { return; } try { requestBootstrapFromPeers(activePeers) .get(DistributedPrimitive.DEFAULT_OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { LOGGER.debug("Failed to bootstrap ec map {}: {}", mapName, ExceptionUtils.getStackTrace(e)); } }
[ "private", "void", "bootstrap", "(", ")", "{", "List", "<", "MemberId", ">", "activePeers", "=", "bootstrapPeersSupplier", ".", "get", "(", ")", ";", "if", "(", "activePeers", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "try", "{", "requestBootstrapFromPeers", "(", "activePeers", ")", ".", "get", "(", "DistributedPrimitive", ".", "DEFAULT_OPERATION_TIMEOUT_MILLIS", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}", "catch", "(", "ExecutionException", "|", "InterruptedException", "|", "TimeoutException", "e", ")", "{", "LOGGER", ".", "debug", "(", "\"Failed to bootstrap ec map {}: {}\"", ",", "mapName", ",", "ExceptionUtils", ".", "getStackTrace", "(", "e", ")", ")", ";", "}", "}" ]
Bootstraps the map to attempt to get in sync with existing instances of the same map on other nodes in the cluster. This is necessary to ensure that a read immediately after the map is created doesn't return a null value.
[ "Bootstraps", "the", "map", "to", "attempt", "to", "get", "in", "sync", "with", "existing", "instances", "of", "the", "same", "map", "on", "other", "nodes", "in", "the", "cluster", ".", "This", "is", "necessary", "to", "ensure", "that", "a", "read", "immediately", "after", "the", "map", "is", "created", "doesn", "t", "return", "a", "null", "value", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/AntiEntropyMapDelegate.java#L721-L732
27,670
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/AntiEntropyMapDelegate.java
AntiEntropyMapDelegate.requestBootstrapFromPeer
private CompletableFuture<Void> requestBootstrapFromPeer(MemberId peer) { LOGGER.trace("Sending bootstrap request to {} for {}", peer, mapName); return clusterCommunicator.<MemberId, Void>send( bootstrapMessageSubject, localMemberId, serializer::encode, serializer::decode, peer) .whenComplete((updates, error) -> { if (error != null) { LOGGER.debug("Bootstrap request to {} failed: {}", peer, error.getMessage()); } }); }
java
private CompletableFuture<Void> requestBootstrapFromPeer(MemberId peer) { LOGGER.trace("Sending bootstrap request to {} for {}", peer, mapName); return clusterCommunicator.<MemberId, Void>send( bootstrapMessageSubject, localMemberId, serializer::encode, serializer::decode, peer) .whenComplete((updates, error) -> { if (error != null) { LOGGER.debug("Bootstrap request to {} failed: {}", peer, error.getMessage()); } }); }
[ "private", "CompletableFuture", "<", "Void", ">", "requestBootstrapFromPeer", "(", "MemberId", "peer", ")", "{", "LOGGER", ".", "trace", "(", "\"Sending bootstrap request to {} for {}\"", ",", "peer", ",", "mapName", ")", ";", "return", "clusterCommunicator", ".", "<", "MemberId", ",", "Void", ">", "send", "(", "bootstrapMessageSubject", ",", "localMemberId", ",", "serializer", "::", "encode", ",", "serializer", "::", "decode", ",", "peer", ")", ".", "whenComplete", "(", "(", "updates", ",", "error", ")", "->", "{", "if", "(", "error", "!=", "null", ")", "{", "LOGGER", ".", "debug", "(", "\"Bootstrap request to {} failed: {}\"", ",", "peer", ",", "error", ".", "getMessage", "(", ")", ")", ";", "}", "}", ")", ";", "}" ]
Requests a bootstrap from the given peer. @param peer the peer from which to request updates @return a future to be completed once the peer has sent bootstrap updates
[ "Requests", "a", "bootstrap", "from", "the", "given", "peer", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/AntiEntropyMapDelegate.java#L785-L798
27,671
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/user/AuthCredentials.java
AuthCredentials.clearSecrets
public void clearSecrets() { if (password != null) { Arrays.fill(password, (byte) '\0'); password = null; } nativeCredentials = null; }
java
public void clearSecrets() { if (password != null) { Arrays.fill(password, (byte) '\0'); password = null; } nativeCredentials = null; }
[ "public", "void", "clearSecrets", "(", ")", "{", "if", "(", "password", "!=", "null", ")", "{", "Arrays", ".", "fill", "(", "password", ",", "(", "byte", ")", "'", "'", ")", ";", "password", "=", "null", ";", "}", "nativeCredentials", "=", "null", ";", "}" ]
Wipe password and native credentials
[ "Wipe", "password", "and", "native", "credentials" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/user/AuthCredentials.java#L126-L133
27,672
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/user/User.java
User.addAttributes
public final void addAttributes(final Map<String,String> attributes) { if(attributes != null) { this.attributes.putAll(attributes); } }
java
public final void addAttributes(final Map<String,String> attributes) { if(attributes != null) { this.attributes.putAll(attributes); } }
[ "public", "final", "void", "addAttributes", "(", "final", "Map", "<", "String", ",", "String", ">", "attributes", ")", "{", "if", "(", "attributes", "!=", "null", ")", "{", "this", ".", "attributes", ".", "putAll", "(", "attributes", ")", ";", "}", "}" ]
Associate this user with a set of roles @param roles The roles
[ "Associate", "this", "user", "with", "a", "set", "of", "roles" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/user/User.java#L145-L149
27,673
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/support/WildcardMatcher.java
WildcardMatcher.matchAny
public static boolean matchAny(final Collection<String> pattern, final String[] candidate, boolean ignoreCase) { for (String string: pattern) { if (matchAny(string, candidate, ignoreCase)) { return true; } } return false; }
java
public static boolean matchAny(final Collection<String> pattern, final String[] candidate, boolean ignoreCase) { for (String string: pattern) { if (matchAny(string, candidate, ignoreCase)) { return true; } } return false; }
[ "public", "static", "boolean", "matchAny", "(", "final", "Collection", "<", "String", ">", "pattern", ",", "final", "String", "[", "]", "candidate", ",", "boolean", "ignoreCase", ")", "{", "for", "(", "String", "string", ":", "pattern", ")", "{", "if", "(", "matchAny", "(", "string", ",", "candidate", ",", "ignoreCase", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
returns true if at least one candidate match at least one pattern @param pattern @param candidate @param ignoreCase @return
[ "returns", "true", "if", "at", "least", "one", "candidate", "match", "at", "least", "one", "pattern" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/support/WildcardMatcher.java#L77-L86
27,674
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/support/WildcardMatcher.java
WildcardMatcher.matchAny
public static boolean matchAny(final String pattern, final String[] candidate, boolean ignoreCase) { for (int i = 0; i < candidate.length; i++) { final String string = candidate[i]; if (match(pattern, string, ignoreCase)) { return true; } } return false; }
java
public static boolean matchAny(final String pattern, final String[] candidate, boolean ignoreCase) { for (int i = 0; i < candidate.length; i++) { final String string = candidate[i]; if (match(pattern, string, ignoreCase)) { return true; } } return false; }
[ "public", "static", "boolean", "matchAny", "(", "final", "String", "pattern", ",", "final", "String", "[", "]", "candidate", ",", "boolean", "ignoreCase", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "candidate", ".", "length", ";", "i", "++", ")", "{", "final", "String", "string", "=", "candidate", "[", "i", "]", ";", "if", "(", "match", "(", "pattern", ",", "string", ",", "ignoreCase", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
return true if at least one candidate matches the given pattern @param pattern @param candidate @param ignoreCase @return
[ "return", "true", "if", "at", "least", "one", "candidate", "matches", "the", "given", "pattern" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/support/WildcardMatcher.java#L168-L178
27,675
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/support/SgUtils.java
SgUtils.forEN
private static Locale forEN() { if ("en".equalsIgnoreCase(Locale.getDefault().getLanguage())) { return Locale.getDefault(); } Locale[] locales = Locale.getAvailableLocales(); for (int i = 0; i != locales.length; i++) { if ("en".equalsIgnoreCase(locales[i].getLanguage())) { return locales[i]; } } return Locale.getDefault(); }
java
private static Locale forEN() { if ("en".equalsIgnoreCase(Locale.getDefault().getLanguage())) { return Locale.getDefault(); } Locale[] locales = Locale.getAvailableLocales(); for (int i = 0; i != locales.length; i++) { if ("en".equalsIgnoreCase(locales[i].getLanguage())) { return locales[i]; } } return Locale.getDefault(); }
[ "private", "static", "Locale", "forEN", "(", ")", "{", "if", "(", "\"en\"", ".", "equalsIgnoreCase", "(", "Locale", ".", "getDefault", "(", ")", ".", "getLanguage", "(", ")", ")", ")", "{", "return", "Locale", ".", "getDefault", "(", ")", ";", "}", "Locale", "[", "]", "locales", "=", "Locale", ".", "getAvailableLocales", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "locales", ".", "length", ";", "i", "++", ")", "{", "if", "(", "\"en\"", ".", "equalsIgnoreCase", "(", "locales", "[", "i", "]", ".", "getLanguage", "(", ")", ")", ")", "{", "return", "locales", "[", "i", "]", ";", "}", "}", "return", "Locale", ".", "getDefault", "(", ")", ";", "}" ]
The Legion of the Bouncy Castle Inc
[ "The", "Legion", "of", "the", "Bouncy", "Castle", "Inc" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/support/SgUtils.java#L50-L67
27,676
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/http/RemoteIpDetector.java
RemoteIpDetector.commaDelimitedListToStringArray
protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) { return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern .split(commaDelimitedStrings); }
java
protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) { return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern .split(commaDelimitedStrings); }
[ "protected", "static", "String", "[", "]", "commaDelimitedListToStringArray", "(", "String", "commaDelimitedStrings", ")", "{", "return", "(", "commaDelimitedStrings", "==", "null", "||", "commaDelimitedStrings", ".", "length", "(", ")", "==", "0", ")", "?", "new", "String", "[", "0", "]", ":", "commaSeparatedValuesPattern", ".", "split", "(", "commaDelimitedStrings", ")", ";", "}" ]
Convert a given comma delimited String into an array of String @return array of String (non <code>null</code>)
[ "Convert", "a", "given", "comma", "delimited", "String", "into", "an", "array", "of", "String" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/http/RemoteIpDetector.java#L50-L53
27,677
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/http/RemoteIpDetector.java
RemoteIpDetector.listToCommaDelimitedString
protected static String listToCommaDelimitedString(List<String> stringList) { if (stringList == null) { return ""; } StringBuilder result = new StringBuilder(); for (Iterator<String> it = stringList.iterator(); it.hasNext();) { Object element = it.next(); if (element != null) { result.append(element); if (it.hasNext()) { result.append(", "); } } } return result.toString(); }
java
protected static String listToCommaDelimitedString(List<String> stringList) { if (stringList == null) { return ""; } StringBuilder result = new StringBuilder(); for (Iterator<String> it = stringList.iterator(); it.hasNext();) { Object element = it.next(); if (element != null) { result.append(element); if (it.hasNext()) { result.append(", "); } } } return result.toString(); }
[ "protected", "static", "String", "listToCommaDelimitedString", "(", "List", "<", "String", ">", "stringList", ")", "{", "if", "(", "stringList", "==", "null", ")", "{", "return", "\"\"", ";", "}", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Iterator", "<", "String", ">", "it", "=", "stringList", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "Object", "element", "=", "it", ".", "next", "(", ")", ";", "if", "(", "element", "!=", "null", ")", "{", "result", ".", "append", "(", "element", ")", ";", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "result", ".", "append", "(", "\", \"", ")", ";", "}", "}", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Convert an array of strings in a comma delimited string
[ "Convert", "an", "array", "of", "strings", "in", "a", "comma", "delimited", "string" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/http/RemoteIpDetector.java#L58-L73
27,678
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/support/LicenseHelper.java
LicenseHelper.validateLicense
public static String validateLicense(String licenseText) throws PGPException { licenseText = licenseText.trim().replaceAll("\\r|\\n", ""); licenseText = licenseText.replace("---- SCHNIPP (Armored PGP signed JSON as base64) ----",""); licenseText = licenseText.replace("---- SCHNAPP ----",""); try { final byte[] armoredPgp = BaseEncoding.base64().decode(licenseText); final ArmoredInputStream in = new ArmoredInputStream(new ByteArrayInputStream(armoredPgp)); // // read the input, making sure we ignore the last newline. // // https://github.com/bcgit/bc-java/blob/master/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java final ByteArrayOutputStream bout = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) >= 0 && in.isClearText()) { bout.write((byte) ch); } final KeyFingerPrintCalculator c = new BcKeyFingerprintCalculator(); final PGPObjectFactory factory = new PGPObjectFactory(in, c); final PGPSignatureList sigL = (PGPSignatureList) factory.nextObject(); final PGPPublicKeyRingCollection pgpRings = new PGPPublicKeyRingCollection(new ArmoredInputStream( LicenseHelper.class.getResourceAsStream("/KEYS")), c); if (sigL == null || pgpRings == null || sigL.size() == 0 || pgpRings.size() == 0) { throw new PGPException("Cannot find license signature"); } final PGPSignature sig = sigL.get(0); final PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID()); if (publicKey == null || sig == null) { throw new PGPException("license signature key mismatch"); } sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey); final ByteArrayOutputStream lineOut = new ByteArrayOutputStream(); final InputStream sigIn = new ByteArrayInputStream(bout.toByteArray()); int lookAhead = readInputLine(lineOut, sigIn); processLine(sig, lineOut.toByteArray()); if (lookAhead != -1) { do { lookAhead = readInputLine(lineOut, lookAhead, sigIn); sig.update((byte) '\r'); sig.update((byte) '\n'); processLine(sig, lineOut.toByteArray()); } while (lookAhead != -1); } if (!sig.verify()) { throw new PGPException("Invalid license signature"); } return bout.toString(); } catch (final Exception e) { throw new PGPException(e.toString(), e); } }
java
public static String validateLicense(String licenseText) throws PGPException { licenseText = licenseText.trim().replaceAll("\\r|\\n", ""); licenseText = licenseText.replace("---- SCHNIPP (Armored PGP signed JSON as base64) ----",""); licenseText = licenseText.replace("---- SCHNAPP ----",""); try { final byte[] armoredPgp = BaseEncoding.base64().decode(licenseText); final ArmoredInputStream in = new ArmoredInputStream(new ByteArrayInputStream(armoredPgp)); // // read the input, making sure we ignore the last newline. // // https://github.com/bcgit/bc-java/blob/master/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java final ByteArrayOutputStream bout = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) >= 0 && in.isClearText()) { bout.write((byte) ch); } final KeyFingerPrintCalculator c = new BcKeyFingerprintCalculator(); final PGPObjectFactory factory = new PGPObjectFactory(in, c); final PGPSignatureList sigL = (PGPSignatureList) factory.nextObject(); final PGPPublicKeyRingCollection pgpRings = new PGPPublicKeyRingCollection(new ArmoredInputStream( LicenseHelper.class.getResourceAsStream("/KEYS")), c); if (sigL == null || pgpRings == null || sigL.size() == 0 || pgpRings.size() == 0) { throw new PGPException("Cannot find license signature"); } final PGPSignature sig = sigL.get(0); final PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID()); if (publicKey == null || sig == null) { throw new PGPException("license signature key mismatch"); } sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey); final ByteArrayOutputStream lineOut = new ByteArrayOutputStream(); final InputStream sigIn = new ByteArrayInputStream(bout.toByteArray()); int lookAhead = readInputLine(lineOut, sigIn); processLine(sig, lineOut.toByteArray()); if (lookAhead != -1) { do { lookAhead = readInputLine(lineOut, lookAhead, sigIn); sig.update((byte) '\r'); sig.update((byte) '\n'); processLine(sig, lineOut.toByteArray()); } while (lookAhead != -1); } if (!sig.verify()) { throw new PGPException("Invalid license signature"); } return bout.toString(); } catch (final Exception e) { throw new PGPException(e.toString(), e); } }
[ "public", "static", "String", "validateLicense", "(", "String", "licenseText", ")", "throws", "PGPException", "{", "licenseText", "=", "licenseText", ".", "trim", "(", ")", ".", "replaceAll", "(", "\"\\\\r|\\\\n\"", ",", "\"\"", ")", ";", "licenseText", "=", "licenseText", ".", "replace", "(", "\"---- SCHNIPP (Armored PGP signed JSON as base64) ----\"", ",", "\"\"", ")", ";", "licenseText", "=", "licenseText", ".", "replace", "(", "\"---- SCHNAPP ----\"", ",", "\"\"", ")", ";", "try", "{", "final", "byte", "[", "]", "armoredPgp", "=", "BaseEncoding", ".", "base64", "(", ")", ".", "decode", "(", "licenseText", ")", ";", "final", "ArmoredInputStream", "in", "=", "new", "ArmoredInputStream", "(", "new", "ByteArrayInputStream", "(", "armoredPgp", ")", ")", ";", "//", "// read the input, making sure we ignore the last newline.", "//", "// https://github.com/bcgit/bc-java/blob/master/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java", "final", "ByteArrayOutputStream", "bout", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "int", "ch", ";", "while", "(", "(", "ch", "=", "in", ".", "read", "(", ")", ")", ">=", "0", "&&", "in", ".", "isClearText", "(", ")", ")", "{", "bout", ".", "write", "(", "(", "byte", ")", "ch", ")", ";", "}", "final", "KeyFingerPrintCalculator", "c", "=", "new", "BcKeyFingerprintCalculator", "(", ")", ";", "final", "PGPObjectFactory", "factory", "=", "new", "PGPObjectFactory", "(", "in", ",", "c", ")", ";", "final", "PGPSignatureList", "sigL", "=", "(", "PGPSignatureList", ")", "factory", ".", "nextObject", "(", ")", ";", "final", "PGPPublicKeyRingCollection", "pgpRings", "=", "new", "PGPPublicKeyRingCollection", "(", "new", "ArmoredInputStream", "(", "LicenseHelper", ".", "class", ".", "getResourceAsStream", "(", "\"/KEYS\"", ")", ")", ",", "c", ")", ";", "if", "(", "sigL", "==", "null", "||", "pgpRings", "==", "null", "||", "sigL", ".", "size", "(", ")", "==", "0", "||", "pgpRings", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "PGPException", "(", "\"Cannot find license signature\"", ")", ";", "}", "final", "PGPSignature", "sig", "=", "sigL", ".", "get", "(", "0", ")", ";", "final", "PGPPublicKey", "publicKey", "=", "pgpRings", ".", "getPublicKey", "(", "sig", ".", "getKeyID", "(", ")", ")", ";", "if", "(", "publicKey", "==", "null", "||", "sig", "==", "null", ")", "{", "throw", "new", "PGPException", "(", "\"license signature key mismatch\"", ")", ";", "}", "sig", ".", "init", "(", "new", "BcPGPContentVerifierBuilderProvider", "(", ")", ",", "publicKey", ")", ";", "final", "ByteArrayOutputStream", "lineOut", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "final", "InputStream", "sigIn", "=", "new", "ByteArrayInputStream", "(", "bout", ".", "toByteArray", "(", ")", ")", ";", "int", "lookAhead", "=", "readInputLine", "(", "lineOut", ",", "sigIn", ")", ";", "processLine", "(", "sig", ",", "lineOut", ".", "toByteArray", "(", ")", ")", ";", "if", "(", "lookAhead", "!=", "-", "1", ")", "{", "do", "{", "lookAhead", "=", "readInputLine", "(", "lineOut", ",", "lookAhead", ",", "sigIn", ")", ";", "sig", ".", "update", "(", "(", "byte", ")", "'", "'", ")", ";", "sig", ".", "update", "(", "(", "byte", ")", "'", "'", ")", ";", "processLine", "(", "sig", ",", "lineOut", ".", "toByteArray", "(", ")", ")", ";", "}", "while", "(", "lookAhead", "!=", "-", "1", ")", ";", "}", "if", "(", "!", "sig", ".", "verify", "(", ")", ")", "{", "throw", "new", "PGPException", "(", "\"Invalid license signature\"", ")", ";", "}", "return", "bout", ".", "toString", "(", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "throw", "new", "PGPException", "(", "e", ".", "toString", "(", ")", ",", "e", ")", ";", "}", "}" ]
Validate pgp signature of license @param licenseText base64 encoded pgp signed license @return The plain license in json (if validation is successful) @throws PGPException if validation fails
[ "Validate", "pgp", "signature", "of", "license" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/support/LicenseHelper.java#L68-L136
27,679
floragunncom/search-guard
src/main/java/com/floragunn/searchguard/compliance/ComplianceConfig.java
ComplianceConfig.writeHistoryEnabledForIndex
public boolean writeHistoryEnabledForIndex(String index) { if(index == null) { return false; } if(searchguardIndex.equals(index)) { return logInternalConfig; } if(auditLogIndex != null && auditLogIndex.equalsIgnoreCase(index)) { return false; } if(auditLogPattern != null) { if(index.equalsIgnoreCase(getExpandedIndexName(auditLogPattern, null))) { return false; } } return WildcardMatcher.matchAny(watchedWriteIndices, index); }
java
public boolean writeHistoryEnabledForIndex(String index) { if(index == null) { return false; } if(searchguardIndex.equals(index)) { return logInternalConfig; } if(auditLogIndex != null && auditLogIndex.equalsIgnoreCase(index)) { return false; } if(auditLogPattern != null) { if(index.equalsIgnoreCase(getExpandedIndexName(auditLogPattern, null))) { return false; } } return WildcardMatcher.matchAny(watchedWriteIndices, index); }
[ "public", "boolean", "writeHistoryEnabledForIndex", "(", "String", "index", ")", "{", "if", "(", "index", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "searchguardIndex", ".", "equals", "(", "index", ")", ")", "{", "return", "logInternalConfig", ";", "}", "if", "(", "auditLogIndex", "!=", "null", "&&", "auditLogIndex", ".", "equalsIgnoreCase", "(", "index", ")", ")", "{", "return", "false", ";", "}", "if", "(", "auditLogPattern", "!=", "null", ")", "{", "if", "(", "index", ".", "equalsIgnoreCase", "(", "getExpandedIndexName", "(", "auditLogPattern", ",", "null", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "WildcardMatcher", ".", "matchAny", "(", "watchedWriteIndices", ",", "index", ")", ";", "}" ]
do not check for isEnabled
[ "do", "not", "check", "for", "isEnabled" ]
f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d
https://github.com/floragunncom/search-guard/blob/f9828004e11dc0e4b6da4dead1fafcf3be8f7f6d/src/main/java/com/floragunn/searchguard/compliance/ComplianceConfig.java#L212-L233
27,680
spring-cloud/spring-cloud-aws
spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/retry/SqlRetryPolicy.java
SqlRetryPolicy.getSqlRetryAbleExceptions
private static Map<Class<? extends Throwable>, Boolean> getSqlRetryAbleExceptions() { Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>(); retryableExceptions.put(SQLTransientException.class, true); retryableExceptions.put(SQLRecoverableException.class, true); retryableExceptions.put(TransientDataAccessException.class, true); retryableExceptions.put(SQLNonTransientConnectionException.class, true); return retryableExceptions; }
java
private static Map<Class<? extends Throwable>, Boolean> getSqlRetryAbleExceptions() { Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>(); retryableExceptions.put(SQLTransientException.class, true); retryableExceptions.put(SQLRecoverableException.class, true); retryableExceptions.put(TransientDataAccessException.class, true); retryableExceptions.put(SQLNonTransientConnectionException.class, true); return retryableExceptions; }
[ "private", "static", "Map", "<", "Class", "<", "?", "extends", "Throwable", ">", ",", "Boolean", ">", "getSqlRetryAbleExceptions", "(", ")", "{", "Map", "<", "Class", "<", "?", "extends", "Throwable", ">", ",", "Boolean", ">", "retryableExceptions", "=", "new", "HashMap", "<>", "(", ")", ";", "retryableExceptions", ".", "put", "(", "SQLTransientException", ".", "class", ",", "true", ")", ";", "retryableExceptions", ".", "put", "(", "SQLRecoverableException", ".", "class", ",", "true", ")", ";", "retryableExceptions", ".", "put", "(", "TransientDataAccessException", ".", "class", ",", "true", ")", ";", "retryableExceptions", ".", "put", "(", "SQLNonTransientConnectionException", ".", "class", ",", "true", ")", ";", "return", "retryableExceptions", ";", "}" ]
Returns all the exceptions for which a retry is useful. @return - Map containing all retryable exceptions for the {@link BinaryExceptionClassifier}
[ "Returns", "all", "the", "exceptions", "for", "which", "a", "retry", "is", "useful", "." ]
26f7ca6c29ac66922f64b37c2bc5ce6f842462ee
https://github.com/spring-cloud/spring-cloud-aws/blob/26f7ca6c29ac66922f64b37c2bc5ce6f842462ee/spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/retry/SqlRetryPolicy.java#L74-L81
27,681
spring-cloud/spring-cloud-aws
spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/rds/AmazonRdsDataSourceFactoryBean.java
AmazonRdsDataSourceFactoryBean.createDataSourceInstance
protected DataSource createDataSourceInstance(String identifier) throws Exception { DBInstance instance = getDbInstance(identifier); return this.dataSourceFactory.createDataSource(fromRdsInstance(instance)); }
java
protected DataSource createDataSourceInstance(String identifier) throws Exception { DBInstance instance = getDbInstance(identifier); return this.dataSourceFactory.createDataSource(fromRdsInstance(instance)); }
[ "protected", "DataSource", "createDataSourceInstance", "(", "String", "identifier", ")", "throws", "Exception", "{", "DBInstance", "instance", "=", "getDbInstance", "(", "identifier", ")", ";", "return", "this", ".", "dataSourceFactory", ".", "createDataSource", "(", "fromRdsInstance", "(", "instance", ")", ")", ";", "}" ]
Creates a data source based in the instance name. The physical information for the data source is retrieved by the name passed as identifier. This method does distinguish between regular amazon rds instances and read-replicas because both meta-data is retrieved on the same way. @param identifier - the database identifier for the data source configured in amazon rds @return a fully configured and initialized {@link javax.sql.DataSource} @throws java.lang.IllegalStateException if no database has been found @throws java.lang.Exception in case of underlying exceptions
[ "Creates", "a", "data", "source", "based", "in", "the", "instance", "name", ".", "The", "physical", "information", "for", "the", "data", "source", "is", "retrieved", "by", "the", "name", "passed", "as", "identifier", ".", "This", "method", "does", "distinguish", "between", "regular", "amazon", "rds", "instances", "and", "read", "-", "replicas", "because", "both", "meta", "-", "data", "is", "retrieved", "on", "the", "same", "way", "." ]
26f7ca6c29ac66922f64b37c2bc5ce6f842462ee
https://github.com/spring-cloud/spring-cloud-aws/blob/26f7ca6c29ac66922f64b37c2bc5ce6f842462ee/spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/rds/AmazonRdsDataSourceFactoryBean.java#L152-L155
27,682
spring-cloud/spring-cloud-aws
spring-cloud-aws-core/src/main/java/org/springframework/cloud/aws/core/env/StackResourceRegistryDetectingResourceIdResolver.java
StackResourceRegistryDetectingResourceIdResolver.resolveToPhysicalResourceId
@Override public String resolveToPhysicalResourceId(String logicalResourceId) { if (this.stackResourceRegistry != null) { String physicalResourceId = this.stackResourceRegistry .lookupPhysicalResourceId(logicalResourceId); if (physicalResourceId != null) { return physicalResourceId; } } return logicalResourceId; }
java
@Override public String resolveToPhysicalResourceId(String logicalResourceId) { if (this.stackResourceRegistry != null) { String physicalResourceId = this.stackResourceRegistry .lookupPhysicalResourceId(logicalResourceId); if (physicalResourceId != null) { return physicalResourceId; } } return logicalResourceId; }
[ "@", "Override", "public", "String", "resolveToPhysicalResourceId", "(", "String", "logicalResourceId", ")", "{", "if", "(", "this", ".", "stackResourceRegistry", "!=", "null", ")", "{", "String", "physicalResourceId", "=", "this", ".", "stackResourceRegistry", ".", "lookupPhysicalResourceId", "(", "logicalResourceId", ")", ";", "if", "(", "physicalResourceId", "!=", "null", ")", "{", "return", "physicalResourceId", ";", "}", "}", "return", "logicalResourceId", ";", "}" ]
Resolves the provided logical resource id to the corresponding physical resource id. If the logical resource id refers to a resource part of any of the configured stacks, the corresponding physical resource id from the stack is returned. If none of the configured stacks contain a resource with the provided logical resource id, or no stacks are configured at all, the logical resource id is returned as the physical resource id. @param logicalResourceId the logical resource id to be resolved @return the physical resource id
[ "Resolves", "the", "provided", "logical", "resource", "id", "to", "the", "corresponding", "physical", "resource", "id", ".", "If", "the", "logical", "resource", "id", "refers", "to", "a", "resource", "part", "of", "any", "of", "the", "configured", "stacks", "the", "corresponding", "physical", "resource", "id", "from", "the", "stack", "is", "returned", ".", "If", "none", "of", "the", "configured", "stacks", "contain", "a", "resource", "with", "the", "provided", "logical", "resource", "id", "or", "no", "stacks", "are", "configured", "at", "all", "the", "logical", "resource", "id", "is", "returned", "as", "the", "physical", "resource", "id", "." ]
26f7ca6c29ac66922f64b37c2bc5ce6f842462ee
https://github.com/spring-cloud/spring-cloud-aws/blob/26f7ca6c29ac66922f64b37c2bc5ce6f842462ee/spring-cloud-aws-core/src/main/java/org/springframework/cloud/aws/core/env/StackResourceRegistryDetectingResourceIdResolver.java#L73-L85
27,683
spring-cloud/spring-cloud-aws
spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/rds/AmazonRdsDataSourceUserTagsFactoryBean.java
AmazonRdsDataSourceUserTagsFactoryBean.getDbInstanceResourceName
private String getDbInstanceResourceName() { String userArn = this.identityManagement.getUser().getUser().getArn(); AmazonResourceName userResourceName = AmazonResourceName.fromString(userArn); AmazonResourceName dbResourceArn = new AmazonResourceName.Builder() .withService("rds").withRegion(getRegion()) .withAccount(userResourceName.getAccount()).withResourceType("db") .withResourceName(getDbInstanceIdentifier()) .withResourceTypeDelimiter(":").build(); return dbResourceArn.toString(); }
java
private String getDbInstanceResourceName() { String userArn = this.identityManagement.getUser().getUser().getArn(); AmazonResourceName userResourceName = AmazonResourceName.fromString(userArn); AmazonResourceName dbResourceArn = new AmazonResourceName.Builder() .withService("rds").withRegion(getRegion()) .withAccount(userResourceName.getAccount()).withResourceType("db") .withResourceName(getDbInstanceIdentifier()) .withResourceTypeDelimiter(":").build(); return dbResourceArn.toString(); }
[ "private", "String", "getDbInstanceResourceName", "(", ")", "{", "String", "userArn", "=", "this", ".", "identityManagement", ".", "getUser", "(", ")", ".", "getUser", "(", ")", ".", "getArn", "(", ")", ";", "AmazonResourceName", "userResourceName", "=", "AmazonResourceName", ".", "fromString", "(", "userArn", ")", ";", "AmazonResourceName", "dbResourceArn", "=", "new", "AmazonResourceName", ".", "Builder", "(", ")", ".", "withService", "(", "\"rds\"", ")", ".", "withRegion", "(", "getRegion", "(", ")", ")", ".", "withAccount", "(", "userResourceName", ".", "getAccount", "(", ")", ")", ".", "withResourceType", "(", "\"db\"", ")", ".", "withResourceName", "(", "getDbInstanceIdentifier", "(", ")", ")", ".", "withResourceTypeDelimiter", "(", "\":\"", ")", ".", "build", "(", ")", ";", "return", "dbResourceArn", ".", "toString", "(", ")", ";", "}" ]
Unfortunately Amazon AWS mandates to use ARN notation to get the tags. Therefore we first need to get the account number through the IAM service and then construct the ARN out of the account no and region @return the arn string used to query the tags
[ "Unfortunately", "Amazon", "AWS", "mandates", "to", "use", "ARN", "notation", "to", "get", "the", "tags", ".", "Therefore", "we", "first", "need", "to", "get", "the", "account", "number", "through", "the", "IAM", "service", "and", "then", "construct", "the", "ARN", "out", "of", "the", "account", "no", "and", "region" ]
26f7ca6c29ac66922f64b37c2bc5ce6f842462ee
https://github.com/spring-cloud/spring-cloud-aws/blob/26f7ca6c29ac66922f64b37c2bc5ce6f842462ee/spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/rds/AmazonRdsDataSourceUserTagsFactoryBean.java#L101-L110
27,684
spring-cloud/spring-cloud-aws
spring-cloud-aws-context/src/main/java/org/springframework/cloud/aws/context/config/xml/ContextCredentialsBeanDefinitionParser.java
ContextCredentialsBeanDefinitionParser.getCredentials
private static BeanDefinition getCredentials(Element credentialsProviderElement, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition("com.amazonaws.auth.BasicAWSCredentials"); builder.addConstructorArgValue(getAttributeValue(ACCESS_KEY_ATTRIBUTE_NAME, credentialsProviderElement, parserContext)); builder.addConstructorArgValue(getAttributeValue(SECRET_KEY_ATTRIBUTE_NAME, credentialsProviderElement, parserContext)); return builder.getBeanDefinition(); }
java
private static BeanDefinition getCredentials(Element credentialsProviderElement, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition("com.amazonaws.auth.BasicAWSCredentials"); builder.addConstructorArgValue(getAttributeValue(ACCESS_KEY_ATTRIBUTE_NAME, credentialsProviderElement, parserContext)); builder.addConstructorArgValue(getAttributeValue(SECRET_KEY_ATTRIBUTE_NAME, credentialsProviderElement, parserContext)); return builder.getBeanDefinition(); }
[ "private", "static", "BeanDefinition", "getCredentials", "(", "Element", "credentialsProviderElement", ",", "ParserContext", "parserContext", ")", "{", "BeanDefinitionBuilder", "builder", "=", "BeanDefinitionBuilder", ".", "rootBeanDefinition", "(", "\"com.amazonaws.auth.BasicAWSCredentials\"", ")", ";", "builder", ".", "addConstructorArgValue", "(", "getAttributeValue", "(", "ACCESS_KEY_ATTRIBUTE_NAME", ",", "credentialsProviderElement", ",", "parserContext", ")", ")", ";", "builder", ".", "addConstructorArgValue", "(", "getAttributeValue", "(", "SECRET_KEY_ATTRIBUTE_NAME", ",", "credentialsProviderElement", ",", "parserContext", ")", ")", ";", "return", "builder", ".", "getBeanDefinition", "(", ")", ";", "}" ]
Creates a bean definition for the credentials object. This methods creates a bean definition instead of the direct implementation to allow property place holder to change any place holder used for the access or secret key. @param credentialsProviderElement - The element that contains the credentials attributes ACCESS_KEY_ATTRIBUTE_NAME and SECRET_KEY_ATTRIBUTE_NAME @param parserContext - Used to report any errors if there is no ACCESS_KEY_ATTRIBUTE_NAME or SECRET_KEY_ATTRIBUTE_NAME available with a valid value @return - the bean definition with an {@link com.amazonaws.auth.BasicAWSCredentials} class
[ "Creates", "a", "bean", "definition", "for", "the", "credentials", "object", ".", "This", "methods", "creates", "a", "bean", "definition", "instead", "of", "the", "direct", "implementation", "to", "allow", "property", "place", "holder", "to", "change", "any", "place", "holder", "used", "for", "the", "access", "or", "secret", "key", "." ]
26f7ca6c29ac66922f64b37c2bc5ce6f842462ee
https://github.com/spring-cloud/spring-cloud-aws/blob/26f7ca6c29ac66922f64b37c2bc5ce6f842462ee/spring-cloud-aws-context/src/main/java/org/springframework/cloud/aws/context/config/xml/ContextCredentialsBeanDefinitionParser.java#L87-L96
27,685
spring-cloud/spring-cloud-aws
spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/datasource/support/MapBasedDatabasePlatformSupport.java
MapBasedDatabasePlatformSupport.getDriverClassNameForDatabase
@Override public String getDriverClassNameForDatabase(DatabaseType databaseType) { Assert.notNull(databaseType, "databaseType must not be null"); String candidate = this.getDriverClassNameMappings().get(databaseType); Assert.notNull(candidate, String.format( "No driver class name found for database :'%s'", databaseType.name())); return candidate; }
java
@Override public String getDriverClassNameForDatabase(DatabaseType databaseType) { Assert.notNull(databaseType, "databaseType must not be null"); String candidate = this.getDriverClassNameMappings().get(databaseType); Assert.notNull(candidate, String.format( "No driver class name found for database :'%s'", databaseType.name())); return candidate; }
[ "@", "Override", "public", "String", "getDriverClassNameForDatabase", "(", "DatabaseType", "databaseType", ")", "{", "Assert", ".", "notNull", "(", "databaseType", ",", "\"databaseType must not be null\"", ")", ";", "String", "candidate", "=", "this", ".", "getDriverClassNameMappings", "(", ")", ".", "get", "(", "databaseType", ")", ";", "Assert", ".", "notNull", "(", "candidate", ",", "String", ".", "format", "(", "\"No driver class name found for database :'%s'\"", ",", "databaseType", ".", "name", "(", ")", ")", ")", ";", "return", "candidate", ";", "}" ]
Returns the driver class for the database platform. @param databaseType - The database type used to lookup the driver class name. Must not be null @return - The driver class name, is never null @throws IllegalArgumentException if there is no driver class name available for the DatabaseType
[ "Returns", "the", "driver", "class", "for", "the", "database", "platform", "." ]
26f7ca6c29ac66922f64b37c2bc5ce6f842462ee
https://github.com/spring-cloud/spring-cloud-aws/blob/26f7ca6c29ac66922f64b37c2bc5ce6f842462ee/spring-cloud-aws-jdbc/src/main/java/org/springframework/cloud/aws/jdbc/datasource/support/MapBasedDatabasePlatformSupport.java#L43-L50
27,686
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/broadcast/CopyBroadcastReceiver.java
CopyBroadcastReceiver.receive
public int receive(final MessageHandler handler) { int messagesReceived = 0; final BroadcastReceiver receiver = this.receiver; final long lastSeenLappedCount = receiver.lappedCount(); if (receiver.receiveNext()) { if (lastSeenLappedCount != receiver.lappedCount()) { throw new IllegalStateException("unable to keep up with broadcast"); } final int length = receiver.length(); final int capacity = scratchBuffer.capacity(); if (length > capacity && !scratchBuffer.isExpandable()) { throw new IllegalStateException( "buffer required length of " + length + " but only has " + capacity); } final int msgTypeId = receiver.typeId(); scratchBuffer.putBytes(0, receiver.buffer(), receiver.offset(), length); if (!receiver.validate()) { throw new IllegalStateException("unable to keep up with broadcast"); } handler.onMessage(msgTypeId, scratchBuffer, 0, length); messagesReceived = 1; } return messagesReceived; }
java
public int receive(final MessageHandler handler) { int messagesReceived = 0; final BroadcastReceiver receiver = this.receiver; final long lastSeenLappedCount = receiver.lappedCount(); if (receiver.receiveNext()) { if (lastSeenLappedCount != receiver.lappedCount()) { throw new IllegalStateException("unable to keep up with broadcast"); } final int length = receiver.length(); final int capacity = scratchBuffer.capacity(); if (length > capacity && !scratchBuffer.isExpandable()) { throw new IllegalStateException( "buffer required length of " + length + " but only has " + capacity); } final int msgTypeId = receiver.typeId(); scratchBuffer.putBytes(0, receiver.buffer(), receiver.offset(), length); if (!receiver.validate()) { throw new IllegalStateException("unable to keep up with broadcast"); } handler.onMessage(msgTypeId, scratchBuffer, 0, length); messagesReceived = 1; } return messagesReceived; }
[ "public", "int", "receive", "(", "final", "MessageHandler", "handler", ")", "{", "int", "messagesReceived", "=", "0", ";", "final", "BroadcastReceiver", "receiver", "=", "this", ".", "receiver", ";", "final", "long", "lastSeenLappedCount", "=", "receiver", ".", "lappedCount", "(", ")", ";", "if", "(", "receiver", ".", "receiveNext", "(", ")", ")", "{", "if", "(", "lastSeenLappedCount", "!=", "receiver", ".", "lappedCount", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"unable to keep up with broadcast\"", ")", ";", "}", "final", "int", "length", "=", "receiver", ".", "length", "(", ")", ";", "final", "int", "capacity", "=", "scratchBuffer", ".", "capacity", "(", ")", ";", "if", "(", "length", ">", "capacity", "&&", "!", "scratchBuffer", ".", "isExpandable", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"buffer required length of \"", "+", "length", "+", "\" but only has \"", "+", "capacity", ")", ";", "}", "final", "int", "msgTypeId", "=", "receiver", ".", "typeId", "(", ")", ";", "scratchBuffer", ".", "putBytes", "(", "0", ",", "receiver", ".", "buffer", "(", ")", ",", "receiver", ".", "offset", "(", ")", ",", "length", ")", ";", "if", "(", "!", "receiver", ".", "validate", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"unable to keep up with broadcast\"", ")", ";", "}", "handler", ".", "onMessage", "(", "msgTypeId", ",", "scratchBuffer", ",", "0", ",", "length", ")", ";", "messagesReceived", "=", "1", ";", "}", "return", "messagesReceived", ";", "}" ]
Receive one message from the broadcast buffer. @param handler to be called for each message received. @return the number of messages that have been received.
[ "Receive", "one", "message", "from", "the", "broadcast", "buffer", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/broadcast/CopyBroadcastReceiver.java#L87-L122
27,687
real-logic/agrona
agrona/src/main/java/org/agrona/Strings.java
Strings.parseIntOrDefault
public static int parseIntOrDefault(final String value, final int defaultValue) { if (null == value) { return defaultValue; } return Integer.parseInt(value); }
java
public static int parseIntOrDefault(final String value, final int defaultValue) { if (null == value) { return defaultValue; } return Integer.parseInt(value); }
[ "public", "static", "int", "parseIntOrDefault", "(", "final", "String", "value", ",", "final", "int", "defaultValue", ")", "{", "if", "(", "null", "==", "value", ")", "{", "return", "defaultValue", ";", "}", "return", "Integer", ".", "parseInt", "(", "value", ")", ";", "}" ]
Parse an int from a String. If the String is null then return the defaultValue. @param value to be parsed @param defaultValue to be used if the String value is null. @return the int value of the string or the default on null.
[ "Parse", "an", "int", "from", "a", "String", ".", "If", "the", "String", "is", "null", "then", "return", "the", "defaultValue", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/Strings.java#L41-L49
27,688
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/HighResolutionClock.java
HighResolutionClock.epochMicros
public static long epochMicros() { final Instant now = Instant.now(); final long seconds = now.getEpochSecond(); final long nanosFromSecond = now.getNano(); return (seconds * 1_000_000) + (nanosFromSecond / 1_000); }
java
public static long epochMicros() { final Instant now = Instant.now(); final long seconds = now.getEpochSecond(); final long nanosFromSecond = now.getNano(); return (seconds * 1_000_000) + (nanosFromSecond / 1_000); }
[ "public", "static", "long", "epochMicros", "(", ")", "{", "final", "Instant", "now", "=", "Instant", ".", "now", "(", ")", ";", "final", "long", "seconds", "=", "now", ".", "getEpochSecond", "(", ")", ";", "final", "long", "nanosFromSecond", "=", "now", ".", "getNano", "(", ")", ";", "return", "(", "seconds", "*", "1_000_000", ")", "+", "(", "nanosFromSecond", "/", "1_000", ")", ";", "}" ]
The number of microseconds since the 1 Jan 1970 UTC. @return the number of microseconds since the 1 Jan 1970 UTC.
[ "The", "number", "of", "microseconds", "since", "the", "1", "Jan", "1970", "UTC", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/HighResolutionClock.java#L42-L49
27,689
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/HighResolutionClock.java
HighResolutionClock.epochNanos
public static long epochNanos() { final Instant now = Instant.now(); final long seconds = now.getEpochSecond(); final long nanosFromSecond = now.getNano(); return (seconds * 1_000_000_000) + nanosFromSecond; }
java
public static long epochNanos() { final Instant now = Instant.now(); final long seconds = now.getEpochSecond(); final long nanosFromSecond = now.getNano(); return (seconds * 1_000_000_000) + nanosFromSecond; }
[ "public", "static", "long", "epochNanos", "(", ")", "{", "final", "Instant", "now", "=", "Instant", ".", "now", "(", ")", ";", "final", "long", "seconds", "=", "now", ".", "getEpochSecond", "(", ")", ";", "final", "long", "nanosFromSecond", "=", "now", ".", "getNano", "(", ")", ";", "return", "(", "seconds", "*", "1_000_000_000", ")", "+", "nanosFromSecond", ";", "}" ]
The number of nanoseconds since the 1 Jan 1970 UTC. @return the number of nanoseconds since the 1 Jan 1970 UTC.
[ "The", "number", "of", "nanoseconds", "since", "the", "1", "Jan", "1970", "UTC", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/HighResolutionClock.java#L56-L63
27,690
real-logic/agrona
agrona/src/main/java/org/agrona/References.java
References.isReferringTo
public static <T> boolean isReferringTo(final Reference<T> ref, final T obj) { return ref.get() == obj; }
java
public static <T> boolean isReferringTo(final Reference<T> ref, final T obj) { return ref.get() == obj; }
[ "public", "static", "<", "T", ">", "boolean", "isReferringTo", "(", "final", "Reference", "<", "T", ">", "ref", ",", "final", "T", "obj", ")", "{", "return", "ref", ".", "get", "(", ")", "==", "obj", ";", "}" ]
Indicate whether a Reference refers to a given object. @param ref The {@link Reference} to be tested. @param obj The object to which the {@link Reference} may, or may not, be referring. @param <T> the class of the referent. @return true if the {@link Reference}'s referent is obj, otherwise false.
[ "Indicate", "whether", "a", "Reference", "refers", "to", "a", "given", "object", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/References.java#L70-L73
27,691
real-logic/agrona
agrona/src/main/java/org/agrona/SystemUtil.java
SystemUtil.isDebuggerAttached
public static boolean isDebuggerAttached() { final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); for (final String arg : runtimeMXBean.getInputArguments()) { if (arg.contains("-agentlib:jdwp")) { return true; } } return false; }
java
public static boolean isDebuggerAttached() { final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); for (final String arg : runtimeMXBean.getInputArguments()) { if (arg.contains("-agentlib:jdwp")) { return true; } } return false; }
[ "public", "static", "boolean", "isDebuggerAttached", "(", ")", "{", "final", "RuntimeMXBean", "runtimeMXBean", "=", "ManagementFactory", ".", "getRuntimeMXBean", "(", ")", ";", "for", "(", "final", "String", "arg", ":", "runtimeMXBean", ".", "getInputArguments", "(", ")", ")", "{", "if", "(", "arg", ".", "contains", "(", "\"-agentlib:jdwp\"", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Is a debugger attached to the JVM? @return true if attached otherwise false.
[ "Is", "a", "debugger", "attached", "to", "the", "JVM?" ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/SystemUtil.java#L104-L117
27,692
real-logic/agrona
agrona/src/main/java/org/agrona/SystemUtil.java
SystemUtil.threadDump
public static String threadDump() { final StringBuilder sb = new StringBuilder(); final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); for (final ThreadInfo info : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE)) { sb.append('"').append(info.getThreadName()).append("\": ").append(info.getThreadState()); for (final StackTraceElement stackTraceElement : info.getStackTrace()) { sb.append("\n at ").append(stackTraceElement.toString()); } sb.append("\n\n"); } return sb.toString(); }
java
public static String threadDump() { final StringBuilder sb = new StringBuilder(); final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); for (final ThreadInfo info : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE)) { sb.append('"').append(info.getThreadName()).append("\": ").append(info.getThreadState()); for (final StackTraceElement stackTraceElement : info.getStackTrace()) { sb.append("\n at ").append(stackTraceElement.toString()); } sb.append("\n\n"); } return sb.toString(); }
[ "public", "static", "String", "threadDump", "(", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "final", "ThreadMXBean", "threadMXBean", "=", "ManagementFactory", ".", "getThreadMXBean", "(", ")", ";", "for", "(", "final", "ThreadInfo", "info", ":", "threadMXBean", ".", "getThreadInfo", "(", "threadMXBean", ".", "getAllThreadIds", "(", ")", ",", "Integer", ".", "MAX_VALUE", ")", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ".", "append", "(", "info", ".", "getThreadName", "(", ")", ")", ".", "append", "(", "\"\\\": \"", ")", ".", "append", "(", "info", ".", "getThreadState", "(", ")", ")", ";", "for", "(", "final", "StackTraceElement", "stackTraceElement", ":", "info", ".", "getStackTrace", "(", ")", ")", "{", "sb", ".", "append", "(", "\"\\n at \"", ")", ".", "append", "(", "stackTraceElement", ".", "toString", "(", ")", ")", ";", "}", "sb", ".", "append", "(", "\"\\n\\n\"", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Get a formatted dump of all threads with associated state and stack traces. @return a formatted dump of all threads with associated state and stack traces.
[ "Get", "a", "formatted", "dump", "of", "all", "threads", "with", "associated", "state", "and", "stack", "traces", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/SystemUtil.java#L140-L158
27,693
real-logic/agrona
agrona/src/main/java/org/agrona/SystemUtil.java
SystemUtil.getSizeAsInt
public static int getSizeAsInt(final String propertyName, final int defaultValue) { final String propertyValue = getProperty(propertyName); if (propertyValue != null) { final long value = parseSize(propertyName, propertyValue); if (value < 0 || value > Integer.MAX_VALUE) { throw new NumberFormatException( propertyName + " must positive and less than Integer.MAX_VALUE :" + value); } return (int)value; } return defaultValue; }
java
public static int getSizeAsInt(final String propertyName, final int defaultValue) { final String propertyValue = getProperty(propertyName); if (propertyValue != null) { final long value = parseSize(propertyName, propertyValue); if (value < 0 || value > Integer.MAX_VALUE) { throw new NumberFormatException( propertyName + " must positive and less than Integer.MAX_VALUE :" + value); } return (int)value; } return defaultValue; }
[ "public", "static", "int", "getSizeAsInt", "(", "final", "String", "propertyName", ",", "final", "int", "defaultValue", ")", "{", "final", "String", "propertyValue", "=", "getProperty", "(", "propertyName", ")", ";", "if", "(", "propertyValue", "!=", "null", ")", "{", "final", "long", "value", "=", "parseSize", "(", "propertyName", ",", "propertyValue", ")", ";", "if", "(", "value", "<", "0", "||", "value", ">", "Integer", ".", "MAX_VALUE", ")", "{", "throw", "new", "NumberFormatException", "(", "propertyName", "+", "\" must positive and less than Integer.MAX_VALUE :\"", "+", "value", ")", ";", "}", "return", "(", "int", ")", "value", ";", "}", "return", "defaultValue", ";", "}" ]
Get a size value as an int from a system property. Supports a 'g', 'm', and 'k' suffix to indicate gigabytes, megabytes, or kilobytes respectively. @param propertyName to lookup. @param defaultValue to be applied if the system property is not set. @return the int value. @throws NumberFormatException if the value is out of range or mal-formatted.
[ "Get", "a", "size", "value", "as", "an", "int", "from", "a", "system", "property", ".", "Supports", "a", "g", "m", "and", "k", "suffix", "to", "indicate", "gigabytes", "megabytes", "or", "kilobytes", "respectively", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/SystemUtil.java#L231-L247
27,694
real-logic/agrona
agrona/src/main/java/org/agrona/SystemUtil.java
SystemUtil.getSizeAsLong
public static long getSizeAsLong(final String propertyName, final long defaultValue) { final String propertyValue = getProperty(propertyName); if (propertyValue != null) { final long value = parseSize(propertyName, propertyValue); if (value < 0) { throw new NumberFormatException(propertyName + " must be positive: " + value); } return value; } return defaultValue; }
java
public static long getSizeAsLong(final String propertyName, final long defaultValue) { final String propertyValue = getProperty(propertyName); if (propertyValue != null) { final long value = parseSize(propertyName, propertyValue); if (value < 0) { throw new NumberFormatException(propertyName + " must be positive: " + value); } return value; } return defaultValue; }
[ "public", "static", "long", "getSizeAsLong", "(", "final", "String", "propertyName", ",", "final", "long", "defaultValue", ")", "{", "final", "String", "propertyValue", "=", "getProperty", "(", "propertyName", ")", ";", "if", "(", "propertyValue", "!=", "null", ")", "{", "final", "long", "value", "=", "parseSize", "(", "propertyName", ",", "propertyValue", ")", ";", "if", "(", "value", "<", "0", ")", "{", "throw", "new", "NumberFormatException", "(", "propertyName", "+", "\" must be positive: \"", "+", "value", ")", ";", "}", "return", "value", ";", "}", "return", "defaultValue", ";", "}" ]
Get a size value as a long from a system property. Supports a 'g', 'm', and 'k' suffix to indicate gigabytes, megabytes, or kilobytes respectively. @param propertyName to lookup. @param defaultValue to be applied if the system property is not set. @return the long value. @throws NumberFormatException if the value is out of range or mal-formatted.
[ "Get", "a", "size", "value", "as", "a", "long", "from", "a", "system", "property", ".", "Supports", "a", "g", "m", "and", "k", "suffix", "to", "indicate", "gigabytes", "megabytes", "or", "kilobytes", "respectively", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/SystemUtil.java#L258-L273
27,695
real-logic/agrona
agrona/src/main/java/org/agrona/SystemUtil.java
SystemUtil.parseSize
public static long parseSize(final String propertyName, final String propertyValue) { final int lengthMinusSuffix = propertyValue.length() - 1; final char lastCharacter = propertyValue.charAt(lengthMinusSuffix); if (Character.isDigit(lastCharacter)) { return Long.valueOf(propertyValue); } final long value = AsciiEncoding.parseLongAscii(propertyValue, 0, lengthMinusSuffix); switch (lastCharacter) { case 'k': case 'K': if (value > MAX_K_VALUE) { throw new NumberFormatException(propertyName + " would overflow long: " + propertyValue); } return value * 1024; case 'm': case 'M': if (value > MAX_M_VALUE) { throw new NumberFormatException(propertyName + " would overflow long: " + propertyValue); } return value * 1024 * 1024; case 'g': case 'G': if (value > MAX_G_VALUE) { throw new NumberFormatException(propertyName + " would overflow long: " + propertyValue); } return value * 1024 * 1024 * 1024; default: throw new NumberFormatException( propertyName + ": " + propertyValue + " should end with: k, m, or g."); } }
java
public static long parseSize(final String propertyName, final String propertyValue) { final int lengthMinusSuffix = propertyValue.length() - 1; final char lastCharacter = propertyValue.charAt(lengthMinusSuffix); if (Character.isDigit(lastCharacter)) { return Long.valueOf(propertyValue); } final long value = AsciiEncoding.parseLongAscii(propertyValue, 0, lengthMinusSuffix); switch (lastCharacter) { case 'k': case 'K': if (value > MAX_K_VALUE) { throw new NumberFormatException(propertyName + " would overflow long: " + propertyValue); } return value * 1024; case 'm': case 'M': if (value > MAX_M_VALUE) { throw new NumberFormatException(propertyName + " would overflow long: " + propertyValue); } return value * 1024 * 1024; case 'g': case 'G': if (value > MAX_G_VALUE) { throw new NumberFormatException(propertyName + " would overflow long: " + propertyValue); } return value * 1024 * 1024 * 1024; default: throw new NumberFormatException( propertyName + ": " + propertyValue + " should end with: k, m, or g."); } }
[ "public", "static", "long", "parseSize", "(", "final", "String", "propertyName", ",", "final", "String", "propertyValue", ")", "{", "final", "int", "lengthMinusSuffix", "=", "propertyValue", ".", "length", "(", ")", "-", "1", ";", "final", "char", "lastCharacter", "=", "propertyValue", ".", "charAt", "(", "lengthMinusSuffix", ")", ";", "if", "(", "Character", ".", "isDigit", "(", "lastCharacter", ")", ")", "{", "return", "Long", ".", "valueOf", "(", "propertyValue", ")", ";", "}", "final", "long", "value", "=", "AsciiEncoding", ".", "parseLongAscii", "(", "propertyValue", ",", "0", ",", "lengthMinusSuffix", ")", ";", "switch", "(", "lastCharacter", ")", "{", "case", "'", "'", ":", "case", "'", "'", ":", "if", "(", "value", ">", "MAX_K_VALUE", ")", "{", "throw", "new", "NumberFormatException", "(", "propertyName", "+", "\" would overflow long: \"", "+", "propertyValue", ")", ";", "}", "return", "value", "*", "1024", ";", "case", "'", "'", ":", "case", "'", "'", ":", "if", "(", "value", ">", "MAX_M_VALUE", ")", "{", "throw", "new", "NumberFormatException", "(", "propertyName", "+", "\" would overflow long: \"", "+", "propertyValue", ")", ";", "}", "return", "value", "*", "1024", "*", "1024", ";", "case", "'", "'", ":", "case", "'", "'", ":", "if", "(", "value", ">", "MAX_G_VALUE", ")", "{", "throw", "new", "NumberFormatException", "(", "propertyName", "+", "\" would overflow long: \"", "+", "propertyValue", ")", ";", "}", "return", "value", "*", "1024", "*", "1024", "*", "1024", ";", "default", ":", "throw", "new", "NumberFormatException", "(", "propertyName", "+", "\": \"", "+", "propertyValue", "+", "\" should end with: k, m, or g.\"", ")", ";", "}", "}" ]
Parse a string representation of a value with optional suffix of 'g', 'm', and 'k' suffix to indicate gigabytes, megabytes, or kilobytes respectively. @param propertyName that associated with the size value. @param propertyValue to be parsed. @return the long value. @throws NumberFormatException if the value is out of range or mal-formatted.
[ "Parse", "a", "string", "representation", "of", "a", "value", "with", "optional", "suffix", "of", "g", "m", "and", "k", "suffix", "to", "indicate", "gigabytes", "megabytes", "or", "kilobytes", "respectively", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/SystemUtil.java#L284-L325
27,696
real-logic/agrona
agrona/src/main/java/org/agrona/IoUtil.java
IoUtil.fill
public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value) { try { final byte[] filler; if (0 != value) { filler = new byte[BLOCK_SIZE]; Arrays.fill(filler, value); } else { filler = FILLER; } final ByteBuffer byteBuffer = ByteBuffer.wrap(filler); fileChannel.position(position); final int blocks = (int)(length / BLOCK_SIZE); final int blockRemainder = (int)(length % BLOCK_SIZE); for (int i = 0; i < blocks; i++) { byteBuffer.position(0); fileChannel.write(byteBuffer); } if (blockRemainder > 0) { byteBuffer.position(0); byteBuffer.limit(blockRemainder); fileChannel.write(byteBuffer); } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
java
public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value) { try { final byte[] filler; if (0 != value) { filler = new byte[BLOCK_SIZE]; Arrays.fill(filler, value); } else { filler = FILLER; } final ByteBuffer byteBuffer = ByteBuffer.wrap(filler); fileChannel.position(position); final int blocks = (int)(length / BLOCK_SIZE); final int blockRemainder = (int)(length % BLOCK_SIZE); for (int i = 0; i < blocks; i++) { byteBuffer.position(0); fileChannel.write(byteBuffer); } if (blockRemainder > 0) { byteBuffer.position(0); byteBuffer.limit(blockRemainder); fileChannel.write(byteBuffer); } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
[ "public", "static", "void", "fill", "(", "final", "FileChannel", "fileChannel", ",", "final", "long", "position", ",", "final", "long", "length", ",", "final", "byte", "value", ")", "{", "try", "{", "final", "byte", "[", "]", "filler", ";", "if", "(", "0", "!=", "value", ")", "{", "filler", "=", "new", "byte", "[", "BLOCK_SIZE", "]", ";", "Arrays", ".", "fill", "(", "filler", ",", "value", ")", ";", "}", "else", "{", "filler", "=", "FILLER", ";", "}", "final", "ByteBuffer", "byteBuffer", "=", "ByteBuffer", ".", "wrap", "(", "filler", ")", ";", "fileChannel", ".", "position", "(", "position", ")", ";", "final", "int", "blocks", "=", "(", "int", ")", "(", "length", "/", "BLOCK_SIZE", ")", ";", "final", "int", "blockRemainder", "=", "(", "int", ")", "(", "length", "%", "BLOCK_SIZE", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "blocks", ";", "i", "++", ")", "{", "byteBuffer", ".", "position", "(", "0", ")", ";", "fileChannel", ".", "write", "(", "byteBuffer", ")", ";", "}", "if", "(", "blockRemainder", ">", "0", ")", "{", "byteBuffer", ".", "position", "(", "0", ")", ";", "byteBuffer", ".", "limit", "(", "blockRemainder", ")", ";", "fileChannel", ".", "write", "(", "byteBuffer", ")", ";", "}", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "}" ]
Fill a region of a file with a given byte value. @param fileChannel to fill @param position at which to start writing. @param length of the region to write. @param value to fill the region with.
[ "Fill", "a", "region", "of", "a", "file", "with", "a", "given", "byte", "value", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/IoUtil.java#L92-L130
27,697
real-logic/agrona
agrona/src/main/java/org/agrona/IoUtil.java
IoUtil.delete
public static void delete(final File file, final boolean ignoreFailures) { if (file.isDirectory()) { final File[] files = file.listFiles(); if (null != files) { for (final File f : files) { delete(f, ignoreFailures); } } } if (!file.delete() && !ignoreFailures) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } }
java
public static void delete(final File file, final boolean ignoreFailures) { if (file.isDirectory()) { final File[] files = file.listFiles(); if (null != files) { for (final File f : files) { delete(f, ignoreFailures); } } } if (!file.delete() && !ignoreFailures) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } }
[ "public", "static", "void", "delete", "(", "final", "File", "file", ",", "final", "boolean", "ignoreFailures", ")", "{", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "final", "File", "[", "]", "files", "=", "file", ".", "listFiles", "(", ")", ";", "if", "(", "null", "!=", "files", ")", "{", "for", "(", "final", "File", "f", ":", "files", ")", "{", "delete", "(", "f", ",", "ignoreFailures", ")", ";", "}", "}", "}", "if", "(", "!", "file", ".", "delete", "(", ")", "&&", "!", "ignoreFailures", ")", "{", "try", "{", "Files", ".", "delete", "(", "file", ".", "toPath", "(", ")", ")", ";", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "}", "}" ]
Recursively delete a file or directory tree. @param file to be deleted. @param ignoreFailures don't throw an exception if a delete fails.
[ "Recursively", "delete", "a", "file", "or", "directory", "tree", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/IoUtil.java#L138-L163
27,698
real-logic/agrona
agrona/src/main/java/org/agrona/IoUtil.java
IoUtil.ensureDirectoryExists
public static void ensureDirectoryExists(final File directory, final String descriptionLabel) { if (!directory.exists()) { if (!directory.mkdirs()) { throw new IllegalArgumentException("could not create " + descriptionLabel + " directory: " + directory); } } }
java
public static void ensureDirectoryExists(final File directory, final String descriptionLabel) { if (!directory.exists()) { if (!directory.mkdirs()) { throw new IllegalArgumentException("could not create " + descriptionLabel + " directory: " + directory); } } }
[ "public", "static", "void", "ensureDirectoryExists", "(", "final", "File", "directory", ",", "final", "String", "descriptionLabel", ")", "{", "if", "(", "!", "directory", ".", "exists", "(", ")", ")", "{", "if", "(", "!", "directory", ".", "mkdirs", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"could not create \"", "+", "descriptionLabel", "+", "\" directory: \"", "+", "directory", ")", ";", "}", "}", "}" ]
Create a directory if it doesn't already exist. @param directory the directory which definitely exists after this method call. @param descriptionLabel to associate with the directory for any exceptions.
[ "Create", "a", "directory", "if", "it", "doesn", "t", "already", "exist", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/IoUtil.java#L171-L180
27,699
real-logic/agrona
agrona/src/main/java/org/agrona/IoUtil.java
IoUtil.deleteIfExists
public static void deleteIfExists(final File file) { if (file.exists()) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } }
java
public static void deleteIfExists(final File file) { if (file.exists()) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } }
[ "public", "static", "void", "deleteIfExists", "(", "final", "File", "file", ")", "{", "if", "(", "file", ".", "exists", "(", ")", ")", "{", "try", "{", "Files", ".", "delete", "(", "file", ".", "toPath", "(", ")", ")", ";", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "LangUtil", ".", "rethrowUnchecked", "(", "ex", ")", ";", "}", "}", "}" ]
Delete file only if it already exists. @param file to delete
[ "Delete", "file", "only", "if", "it", "already", "exists", "." ]
d1ea76e6e3598cd6a0d34879687652ef123f639b
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/IoUtil.java#L211-L224