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,400
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java
SegmentedJournal.getNextSegment
JournalSegment<E> getNextSegment(long index) { Map.Entry<Long, JournalSegment<E>> nextSegment = segments.higherEntry(index); return nextSegment != null ? nextSegment.getValue() : null; }
java
JournalSegment<E> getNextSegment(long index) { Map.Entry<Long, JournalSegment<E>> nextSegment = segments.higherEntry(index); return nextSegment != null ? nextSegment.getValue() : null; }
[ "JournalSegment", "<", "E", ">", "getNextSegment", "(", "long", "index", ")", "{", "Map", ".", "Entry", "<", "Long", ",", "JournalSegment", "<", "E", ">", ">", "nextSegment", "=", "segments", ".", "higherEntry", "(", "index", ")", ";", "return", "nextSegment", "!=", "null", "?", "nextSegment", ".", "getValue", "(", ")", ":", "null", ";", "}" ]
Returns the segment following the segment with the given ID. @param index The segment index with which to look up the next segment. @return The next segment for the given index.
[ "Returns", "the", "segment", "following", "the", "segment", "with", "the", "given", "ID", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L382-L385
27,401
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java
SegmentedJournal.removeSegment
synchronized void removeSegment(JournalSegment segment) { segments.remove(segment.index()); segment.close(); segment.delete(); resetCurrentSegment(); }
java
synchronized void removeSegment(JournalSegment segment) { segments.remove(segment.index()); segment.close(); segment.delete(); resetCurrentSegment(); }
[ "synchronized", "void", "removeSegment", "(", "JournalSegment", "segment", ")", "{", "segments", ".", "remove", "(", "segment", ".", "index", "(", ")", ")", ";", "segment", ".", "close", "(", ")", ";", "segment", ".", "delete", "(", ")", ";", "resetCurrentSegment", "(", ")", ";", "}" ]
Removes a segment. @param segment The segment to remove.
[ "Removes", "a", "segment", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L413-L418
27,402
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java
SegmentedJournal.newSegment
protected JournalSegment<E> newSegment(JournalSegmentFile segmentFile, JournalSegmentDescriptor descriptor) { return new JournalSegment<>(segmentFile, descriptor, storageLevel, maxEntrySize, indexDensity, namespace); }
java
protected JournalSegment<E> newSegment(JournalSegmentFile segmentFile, JournalSegmentDescriptor descriptor) { return new JournalSegment<>(segmentFile, descriptor, storageLevel, maxEntrySize, indexDensity, namespace); }
[ "protected", "JournalSegment", "<", "E", ">", "newSegment", "(", "JournalSegmentFile", "segmentFile", ",", "JournalSegmentDescriptor", "descriptor", ")", "{", "return", "new", "JournalSegment", "<>", "(", "segmentFile", ",", "descriptor", ",", "storageLevel", ",", "maxEntrySize", ",", "indexDensity", ",", "namespace", ")", ";", "}" ]
Creates a new segment instance. @param segmentFile The segment file. @param descriptor The segment descriptor. @return The segment instance.
[ "Creates", "a", "new", "segment", "instance", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L462-L464
27,403
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java
SegmentedJournal.resetHead
void resetHead(long index) { for (SegmentedJournalReader reader : readers) { if (reader.getNextIndex() < index) { reader.reset(index); } } }
java
void resetHead(long index) { for (SegmentedJournalReader reader : readers) { if (reader.getNextIndex() < index) { reader.reset(index); } } }
[ "void", "resetHead", "(", "long", "index", ")", "{", "for", "(", "SegmentedJournalReader", "reader", ":", "readers", ")", "{", "if", "(", "reader", ".", "getNextIndex", "(", ")", "<", "index", ")", "{", "reader", ".", "reset", "(", "index", ")", ";", "}", "}", "}" ]
Resets journal readers to the given head. @param index The index at which to reset readers.
[ "Resets", "journal", "readers", "to", "the", "given", "head", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L554-L560
27,404
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java
SegmentedJournal.resetTail
void resetTail(long index) { for (SegmentedJournalReader reader : readers) { if (reader.getNextIndex() >= index) { reader.reset(index); } } }
java
void resetTail(long index) { for (SegmentedJournalReader reader : readers) { if (reader.getNextIndex() >= index) { reader.reset(index); } } }
[ "void", "resetTail", "(", "long", "index", ")", "{", "for", "(", "SegmentedJournalReader", "reader", ":", "readers", ")", "{", "if", "(", "reader", ".", "getNextIndex", "(", ")", ">=", "index", ")", "{", "reader", ".", "reset", "(", "index", ")", ";", "}", "}", "}" ]
Resets journal readers to the given tail. @param index The index at which to reset readers.
[ "Resets", "journal", "readers", "to", "the", "given", "tail", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L567-L573
27,405
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java
SegmentedJournal.isCompactable
public boolean isCompactable(long index) { Map.Entry<Long, JournalSegment<E>> segmentEntry = segments.floorEntry(index); return segmentEntry != null && segments.headMap(segmentEntry.getValue().index()).size() > 0; }
java
public boolean isCompactable(long index) { Map.Entry<Long, JournalSegment<E>> segmentEntry = segments.floorEntry(index); return segmentEntry != null && segments.headMap(segmentEntry.getValue().index()).size() > 0; }
[ "public", "boolean", "isCompactable", "(", "long", "index", ")", "{", "Map", ".", "Entry", "<", "Long", ",", "JournalSegment", "<", "E", ">", ">", "segmentEntry", "=", "segments", ".", "floorEntry", "(", "index", ")", ";", "return", "segmentEntry", "!=", "null", "&&", "segments", ".", "headMap", "(", "segmentEntry", ".", "getValue", "(", ")", ".", "index", "(", ")", ")", ".", "size", "(", ")", ">", "0", ";", "}" ]
Returns a boolean indicating whether a segment can be removed from the journal prior to the given index. @param index the index from which to remove segments @return indicates whether a segment can be removed from the journal
[ "Returns", "a", "boolean", "indicating", "whether", "a", "segment", "can", "be", "removed", "from", "the", "journal", "prior", "to", "the", "given", "index", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L590-L593
27,406
atomix/atomix
storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java
SegmentedJournal.getCompactableIndex
public long getCompactableIndex(long index) { Map.Entry<Long, JournalSegment<E>> segmentEntry = segments.floorEntry(index); return segmentEntry != null ? segmentEntry.getValue().index() : 0; }
java
public long getCompactableIndex(long index) { Map.Entry<Long, JournalSegment<E>> segmentEntry = segments.floorEntry(index); return segmentEntry != null ? segmentEntry.getValue().index() : 0; }
[ "public", "long", "getCompactableIndex", "(", "long", "index", ")", "{", "Map", ".", "Entry", "<", "Long", ",", "JournalSegment", "<", "E", ">", ">", "segmentEntry", "=", "segments", ".", "floorEntry", "(", "index", ")", ";", "return", "segmentEntry", "!=", "null", "?", "segmentEntry", ".", "getValue", "(", ")", ".", "index", "(", ")", ":", "0", ";", "}" ]
Returns the index of the last segment in the log. @param index the compaction index @return the starting index of the last segment in the log
[ "Returns", "the", "index", "of", "the", "last", "segment", "in", "the", "log", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/journal/SegmentedJournal.java#L601-L604
27,407
atomix/atomix
cluster/src/main/java/io/atomix/cluster/impl/PhiAccrualFailureDetector.java
PhiAccrualFailureDetector.report
public void report(long arrivalTime) { checkArgument(arrivalTime >= 0, "arrivalTime must not be negative"); long latestHeartbeat = history.latestHeartbeatTime(); history.samples().addValue(arrivalTime - latestHeartbeat); history.setLatestHeartbeatTime(arrivalTime); }
java
public void report(long arrivalTime) { checkArgument(arrivalTime >= 0, "arrivalTime must not be negative"); long latestHeartbeat = history.latestHeartbeatTime(); history.samples().addValue(arrivalTime - latestHeartbeat); history.setLatestHeartbeatTime(arrivalTime); }
[ "public", "void", "report", "(", "long", "arrivalTime", ")", "{", "checkArgument", "(", "arrivalTime", ">=", "0", ",", "\"arrivalTime must not be negative\"", ")", ";", "long", "latestHeartbeat", "=", "history", ".", "latestHeartbeatTime", "(", ")", ";", "history", ".", "samples", "(", ")", ".", "addValue", "(", "arrivalTime", "-", "latestHeartbeat", ")", ";", "history", ".", "setLatestHeartbeatTime", "(", "arrivalTime", ")", ";", "}" ]
Report a new heart beat for the specified node id. @param arrivalTime arrival time
[ "Report", "a", "new", "heart", "beat", "for", "the", "specified", "node", "id", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/impl/PhiAccrualFailureDetector.java#L89-L94
27,408
atomix/atomix
cluster/src/main/java/io/atomix/cluster/impl/PhiAccrualFailureDetector.java
PhiAccrualFailureDetector.phi
public double phi() { long latestHeartbeat = history.latestHeartbeatTime(); DescriptiveStatistics samples = history.samples(); if (samples.getN() < minSamples) { return 0.0; } return computePhi(samples, latestHeartbeat, System.currentTimeMillis()); }
java
public double phi() { long latestHeartbeat = history.latestHeartbeatTime(); DescriptiveStatistics samples = history.samples(); if (samples.getN() < minSamples) { return 0.0; } return computePhi(samples, latestHeartbeat, System.currentTimeMillis()); }
[ "public", "double", "phi", "(", ")", "{", "long", "latestHeartbeat", "=", "history", ".", "latestHeartbeatTime", "(", ")", ";", "DescriptiveStatistics", "samples", "=", "history", ".", "samples", "(", ")", ";", "if", "(", "samples", ".", "getN", "(", ")", "<", "minSamples", ")", "{", "return", "0.0", ";", "}", "return", "computePhi", "(", "samples", ",", "latestHeartbeat", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "}" ]
Compute phi for the specified node id. @return phi value
[ "Compute", "phi", "for", "the", "specified", "node", "id", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/impl/PhiAccrualFailureDetector.java#L101-L108
27,409
atomix/atomix
cluster/src/main/java/io/atomix/cluster/messaging/impl/HandlerRegistry.java
HandlerRegistry.register
void register(String type, BiConsumer<ProtocolRequest, ServerConnection> handler) { handlers.put(type, handler); }
java
void register(String type, BiConsumer<ProtocolRequest, ServerConnection> handler) { handlers.put(type, handler); }
[ "void", "register", "(", "String", "type", ",", "BiConsumer", "<", "ProtocolRequest", ",", "ServerConnection", ">", "handler", ")", "{", "handlers", ".", "put", "(", "type", ",", "handler", ")", ";", "}" ]
Registers a message type handler. @param type the message type @param handler the message handler
[ "Registers", "a", "message", "type", "handler", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/messaging/impl/HandlerRegistry.java#L34-L36
27,410
atomix/atomix
core/src/main/java/io/atomix/core/impl/CoreTransactionService.java
CoreTransactionService.onMembershipChange
private void onMembershipChange(ClusterMembershipEvent event) { if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) { recoverTransactions(transactions.entrySet().iterator(), event.subject().id()); } }
java
private void onMembershipChange(ClusterMembershipEvent event) { if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) { recoverTransactions(transactions.entrySet().iterator(), event.subject().id()); } }
[ "private", "void", "onMembershipChange", "(", "ClusterMembershipEvent", "event", ")", "{", "if", "(", "event", ".", "type", "(", ")", "==", "ClusterMembershipEvent", ".", "Type", ".", "MEMBER_REMOVED", ")", "{", "recoverTransactions", "(", "transactions", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ",", "event", ".", "subject", "(", ")", ".", "id", "(", ")", ")", ";", "}", "}" ]
Handles a cluster membership change event.
[ "Handles", "a", "cluster", "membership", "change", "event", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/impl/CoreTransactionService.java#L185-L189
27,411
atomix/atomix
core/src/main/java/io/atomix/core/impl/CoreTransactionService.java
CoreTransactionService.recoverTransactions
private void recoverTransactions(AsyncIterator<Map.Entry<TransactionId, Versioned<TransactionInfo>>> iterator, MemberId memberId) { iterator.next().thenAccept(entry -> { if (entry.getValue().value().coordinator.equals(memberId)) { recoverTransaction(entry.getKey(), entry.getValue().value()); } recoverTransactions(iterator, memberId); }); }
java
private void recoverTransactions(AsyncIterator<Map.Entry<TransactionId, Versioned<TransactionInfo>>> iterator, MemberId memberId) { iterator.next().thenAccept(entry -> { if (entry.getValue().value().coordinator.equals(memberId)) { recoverTransaction(entry.getKey(), entry.getValue().value()); } recoverTransactions(iterator, memberId); }); }
[ "private", "void", "recoverTransactions", "(", "AsyncIterator", "<", "Map", ".", "Entry", "<", "TransactionId", ",", "Versioned", "<", "TransactionInfo", ">", ">", ">", "iterator", ",", "MemberId", "memberId", ")", "{", "iterator", ".", "next", "(", ")", ".", "thenAccept", "(", "entry", "->", "{", "if", "(", "entry", ".", "getValue", "(", ")", ".", "value", "(", ")", ".", "coordinator", ".", "equals", "(", "memberId", ")", ")", "{", "recoverTransaction", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "value", "(", ")", ")", ";", "}", "recoverTransactions", "(", "iterator", ",", "memberId", ")", ";", "}", ")", ";", "}" ]
Recursively recovers transactions using the given iterator. @param iterator the asynchronous iterator from which to recover transactions @param memberId the transaction member ID
[ "Recursively", "recovers", "transactions", "using", "the", "given", "iterator", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/impl/CoreTransactionService.java#L197-L204
27,412
atomix/atomix
core/src/main/java/io/atomix/core/impl/CoreTransactionService.java
CoreTransactionService.recoverTransaction
private void recoverTransaction(TransactionId transactionId, TransactionInfo transactionInfo) { switch (transactionInfo.state) { case PREPARING: completePreparingTransaction(transactionId); break; case COMMITTING: completeCommittingTransaction(transactionId); break; case ROLLING_BACK: completeRollingBackTransaction(transactionId); break; default: break; } }
java
private void recoverTransaction(TransactionId transactionId, TransactionInfo transactionInfo) { switch (transactionInfo.state) { case PREPARING: completePreparingTransaction(transactionId); break; case COMMITTING: completeCommittingTransaction(transactionId); break; case ROLLING_BACK: completeRollingBackTransaction(transactionId); break; default: break; } }
[ "private", "void", "recoverTransaction", "(", "TransactionId", "transactionId", ",", "TransactionInfo", "transactionInfo", ")", "{", "switch", "(", "transactionInfo", ".", "state", ")", "{", "case", "PREPARING", ":", "completePreparingTransaction", "(", "transactionId", ")", ";", "break", ";", "case", "COMMITTING", ":", "completeCommittingTransaction", "(", "transactionId", ")", ";", "break", ";", "case", "ROLLING_BACK", ":", "completeRollingBackTransaction", "(", "transactionId", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}" ]
Recovers and completes the given transaction. @param transactionId the transaction identifier @param transactionInfo the transaction info
[ "Recovers", "and", "completes", "the", "given", "transaction", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/impl/CoreTransactionService.java#L212-L226
27,413
atomix/atomix
core/src/main/java/io/atomix/core/impl/CoreTransactionService.java
CoreTransactionService.completeTransaction
@SuppressWarnings("unchecked") private CompletableFuture<Void> completeTransaction( TransactionId transactionId, TransactionState expectState, Function<TransactionInfo, TransactionInfo> updateFunction, Predicate<TransactionInfo> updatedPredicate, BiFunction<TransactionId, Transactional<?>, CompletableFuture<Void>> completionFunction) { return transactions.compute(transactionId, (id, info) -> { if (info == null) { return null; } else if (info.state == expectState) { return updateFunction.apply(info); } else { return info; } }).thenCompose(value -> { if (value != null && updatedPredicate.test(value.value())) { return Futures.allOf(value.value().participants.stream() .map(participantInfo -> completeParticipant(participantInfo, info -> completionFunction.apply(transactionId, info)))) .thenApply(v -> null); } return Futures.exceptionalFuture(new TransactionException("Failed to acquire transaction lock")); }); }
java
@SuppressWarnings("unchecked") private CompletableFuture<Void> completeTransaction( TransactionId transactionId, TransactionState expectState, Function<TransactionInfo, TransactionInfo> updateFunction, Predicate<TransactionInfo> updatedPredicate, BiFunction<TransactionId, Transactional<?>, CompletableFuture<Void>> completionFunction) { return transactions.compute(transactionId, (id, info) -> { if (info == null) { return null; } else if (info.state == expectState) { return updateFunction.apply(info); } else { return info; } }).thenCompose(value -> { if (value != null && updatedPredicate.test(value.value())) { return Futures.allOf(value.value().participants.stream() .map(participantInfo -> completeParticipant(participantInfo, info -> completionFunction.apply(transactionId, info)))) .thenApply(v -> null); } return Futures.exceptionalFuture(new TransactionException("Failed to acquire transaction lock")); }); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "CompletableFuture", "<", "Void", ">", "completeTransaction", "(", "TransactionId", "transactionId", ",", "TransactionState", "expectState", ",", "Function", "<", "TransactionInfo", ",", "TransactionInfo", ">", "updateFunction", ",", "Predicate", "<", "TransactionInfo", ">", "updatedPredicate", ",", "BiFunction", "<", "TransactionId", ",", "Transactional", "<", "?", ">", ",", "CompletableFuture", "<", "Void", ">", ">", "completionFunction", ")", "{", "return", "transactions", ".", "compute", "(", "transactionId", ",", "(", "id", ",", "info", ")", "->", "{", "if", "(", "info", "==", "null", ")", "{", "return", "null", ";", "}", "else", "if", "(", "info", ".", "state", "==", "expectState", ")", "{", "return", "updateFunction", ".", "apply", "(", "info", ")", ";", "}", "else", "{", "return", "info", ";", "}", "}", ")", ".", "thenCompose", "(", "value", "->", "{", "if", "(", "value", "!=", "null", "&&", "updatedPredicate", ".", "test", "(", "value", ".", "value", "(", ")", ")", ")", "{", "return", "Futures", ".", "allOf", "(", "value", ".", "value", "(", ")", ".", "participants", ".", "stream", "(", ")", ".", "map", "(", "participantInfo", "->", "completeParticipant", "(", "participantInfo", ",", "info", "->", "completionFunction", ".", "apply", "(", "transactionId", ",", "info", ")", ")", ")", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}", "return", "Futures", ".", "exceptionalFuture", "(", "new", "TransactionException", "(", "\"Failed to acquire transaction lock\"", ")", ")", ";", "}", ")", ";", "}" ]
Completes a transaction by modifying the transaction state to change ownership to this member and then completing the transaction based on the existing transaction state.
[ "Completes", "a", "transaction", "by", "modifying", "the", "transaction", "state", "to", "change", "ownership", "to", "this", "member", "and", "then", "completing", "the", "transaction", "based", "on", "the", "existing", "transaction", "state", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/impl/CoreTransactionService.java#L307-L330
27,414
atomix/atomix
rest/src/main/java/io/atomix/rest/resources/DocumentTreeResource.java
DocumentTreeResource.getDocumentPath
private DocumentPath getDocumentPath(List<PathSegment> params) { if (params.isEmpty()) { return DocumentPath.ROOT; } else { return DocumentPath.from(params.stream().map(PathSegment::getPath).collect(Collectors.toList())); } }
java
private DocumentPath getDocumentPath(List<PathSegment> params) { if (params.isEmpty()) { return DocumentPath.ROOT; } else { return DocumentPath.from(params.stream().map(PathSegment::getPath).collect(Collectors.toList())); } }
[ "private", "DocumentPath", "getDocumentPath", "(", "List", "<", "PathSegment", ">", "params", ")", "{", "if", "(", "params", ".", "isEmpty", "(", ")", ")", "{", "return", "DocumentPath", ".", "ROOT", ";", "}", "else", "{", "return", "DocumentPath", ".", "from", "(", "params", ".", "stream", "(", ")", ".", "map", "(", "PathSegment", "::", "getPath", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "}", "}" ]
Returns a document path for the given path params.
[ "Returns", "a", "document", "path", "for", "the", "given", "path", "params", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/rest/src/main/java/io/atomix/rest/resources/DocumentTreeResource.java#L63-L69
27,415
atomix/atomix
storage/src/main/java/io/atomix/storage/buffer/HeapBytes.java
HeapBytes.allocate
public static HeapBytes allocate(int size) { if (size > MAX_SIZE) { throw new IllegalArgumentException("size cannot for HeapBytes cannot be greater than " + MAX_SIZE); } return new HeapBytes(ByteBuffer.allocate((int) size)); }
java
public static HeapBytes allocate(int size) { if (size > MAX_SIZE) { throw new IllegalArgumentException("size cannot for HeapBytes cannot be greater than " + MAX_SIZE); } return new HeapBytes(ByteBuffer.allocate((int) size)); }
[ "public", "static", "HeapBytes", "allocate", "(", "int", "size", ")", "{", "if", "(", "size", ">", "MAX_SIZE", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"size cannot for HeapBytes cannot be greater than \"", "+", "MAX_SIZE", ")", ";", "}", "return", "new", "HeapBytes", "(", "ByteBuffer", ".", "allocate", "(", "(", "int", ")", "size", ")", ")", ";", "}" ]
Allocates a new heap byte array. @param size The count of the buffer to allocate (in bytes). @return The heap buffer. @throws IllegalArgumentException If {@code count} is greater than the maximum allowed count for an array on the Java heap - {@code Integer.MAX_VALUE - 5}
[ "Allocates", "a", "new", "heap", "byte", "array", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/buffer/HeapBytes.java#L34-L39
27,416
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/system/MetaStore.java
MetaStore.loadVote
public synchronized MemberId loadVote() { String id = metadataBuffer.readString(8); return id != null ? MemberId.from(id) : null; }
java
public synchronized MemberId loadVote() { String id = metadataBuffer.readString(8); return id != null ? MemberId.from(id) : null; }
[ "public", "synchronized", "MemberId", "loadVote", "(", ")", "{", "String", "id", "=", "metadataBuffer", ".", "readString", "(", "8", ")", ";", "return", "id", "!=", "null", "?", "MemberId", ".", "from", "(", "id", ")", ":", "null", ";", "}" ]
Loads the last vote for the server. @return The last vote for the server.
[ "Loads", "the", "last", "vote", "for", "the", "server", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/system/MetaStore.java#L101-L104
27,417
atomix/atomix
rest/src/main/java/io/atomix/rest/impl/EventLog.java
EventLog.nextEvent
public CompletableFuture<E> nextEvent() { E event = events.poll(); if (event != null) { return CompletableFuture.completedFuture(event); } else { CompletableFuture<E> future = new CompletableFuture<>(); futures.add(future); return future; } }
java
public CompletableFuture<E> nextEvent() { E event = events.poll(); if (event != null) { return CompletableFuture.completedFuture(event); } else { CompletableFuture<E> future = new CompletableFuture<>(); futures.add(future); return future; } }
[ "public", "CompletableFuture", "<", "E", ">", "nextEvent", "(", ")", "{", "E", "event", "=", "events", ".", "poll", "(", ")", ";", "if", "(", "event", "!=", "null", ")", "{", "return", "CompletableFuture", ".", "completedFuture", "(", "event", ")", ";", "}", "else", "{", "CompletableFuture", "<", "E", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "futures", ".", "add", "(", "future", ")", ";", "return", "future", ";", "}", "}" ]
Completes the given response with the next event. @return a future to be completed with the next event
[ "Completes", "the", "given", "response", "with", "the", "next", "event", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/rest/src/main/java/io/atomix/rest/impl/EventLog.java#L60-L69
27,418
atomix/atomix
rest/src/main/java/io/atomix/rest/impl/EventLog.java
EventLog.addEvent
public void addEvent(E event) { CompletableFuture<E> future = futures.poll(); if (future != null) { future.complete(event); } else { events.add(event); if (events.size() > 100) { events.remove(); } } }
java
public void addEvent(E event) { CompletableFuture<E> future = futures.poll(); if (future != null) { future.complete(event); } else { events.add(event); if (events.size() > 100) { events.remove(); } } }
[ "public", "void", "addEvent", "(", "E", "event", ")", "{", "CompletableFuture", "<", "E", ">", "future", "=", "futures", ".", "poll", "(", ")", ";", "if", "(", "future", "!=", "null", ")", "{", "future", ".", "complete", "(", "event", ")", ";", "}", "else", "{", "events", ".", "add", "(", "event", ")", ";", "if", "(", "events", ".", "size", "(", ")", ">", "100", ")", "{", "events", ".", "remove", "(", ")", ";", "}", "}", "}" ]
Adds an event to the log. @param event the event to add
[ "Adds", "an", "event", "to", "the", "log", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/rest/src/main/java/io/atomix/rest/impl/EventLog.java#L76-L86
27,419
atomix/atomix
utils/src/main/java/io/atomix/utils/memory/MappedMemory.java
MappedMemory.allocate
public static MappedMemory allocate(File file, FileChannel.MapMode mode, int size) { if (size > MAX_SIZE) { throw new IllegalArgumentException("size cannot be greater than " + MAX_SIZE); } return new MappedMemoryAllocator(file, mode).allocate(size); }
java
public static MappedMemory allocate(File file, FileChannel.MapMode mode, int size) { if (size > MAX_SIZE) { throw new IllegalArgumentException("size cannot be greater than " + MAX_SIZE); } return new MappedMemoryAllocator(file, mode).allocate(size); }
[ "public", "static", "MappedMemory", "allocate", "(", "File", "file", ",", "FileChannel", ".", "MapMode", "mode", ",", "int", "size", ")", "{", "if", "(", "size", ">", "MAX_SIZE", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"size cannot be greater than \"", "+", "MAX_SIZE", ")", ";", "}", "return", "new", "MappedMemoryAllocator", "(", "file", ",", "mode", ")", ".", "allocate", "(", "size", ")", ";", "}" ]
Allocates memory mapped to a file on disk. @param file The file to which to map memory. @param mode The mode with which to map memory. @param size The count of the memory to map. @return The mapped memory. @throws IllegalArgumentException If {@code count} is greater than {@link MappedMemory#MAX_SIZE}
[ "Allocates", "memory", "mapped", "to", "a", "file", "on", "disk", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/memory/MappedMemory.java#L61-L66
27,420
atomix/atomix
rest/src/main/java/io/atomix/rest/resources/LeaderElectionResource.java
LeaderElectionResource.getEventLogName
private String getEventLogName(String name, String id) { return String.format("%s-%s", name, id); }
java
private String getEventLogName(String name, String id) { return String.format("%s-%s", name, id); }
[ "private", "String", "getEventLogName", "(", "String", "name", ",", "String", "id", ")", "{", "return", "String", ".", "format", "(", "\"%s-%s\"", ",", "name", ",", "id", ")", ";", "}" ]
Returns an event log name for the given identifier.
[ "Returns", "an", "event", "log", "name", "for", "the", "given", "identifier", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/rest/src/main/java/io/atomix/rest/resources/LeaderElectionResource.java#L60-L62
27,421
atomix/atomix
rest/src/main/java/io/atomix/rest/resources/LeaderElectionResource.java
LeaderElectionResource.consumeNextEvent
private void consumeNextEvent( EventLog<LeadershipEventListener<String>, LeadershipEvent<String>> eventLog, String name, String id, AsyncResponse response) { eventLog.nextEvent().whenComplete((event, error) -> { if (error == null) { if (event.newLeadership().leader() != null && event.newLeadership().leader().id().equals(id)) { response.resume(Response.ok(new LeadershipResponse(event.newLeadership())).build()); } else if (event.newLeadership().candidates().stream().noneMatch(c -> c.equals(id))) { getPrimitive(name).thenCompose(election -> election.removeListener(eventLog.listener())).whenComplete((removeResult, removeError) -> { response.resume(Response.status(Status.NOT_FOUND).build()); }); } } else { response.resume(Response.status(Status.NOT_FOUND).build()); } }); }
java
private void consumeNextEvent( EventLog<LeadershipEventListener<String>, LeadershipEvent<String>> eventLog, String name, String id, AsyncResponse response) { eventLog.nextEvent().whenComplete((event, error) -> { if (error == null) { if (event.newLeadership().leader() != null && event.newLeadership().leader().id().equals(id)) { response.resume(Response.ok(new LeadershipResponse(event.newLeadership())).build()); } else if (event.newLeadership().candidates().stream().noneMatch(c -> c.equals(id))) { getPrimitive(name).thenCompose(election -> election.removeListener(eventLog.listener())).whenComplete((removeResult, removeError) -> { response.resume(Response.status(Status.NOT_FOUND).build()); }); } } else { response.resume(Response.status(Status.NOT_FOUND).build()); } }); }
[ "private", "void", "consumeNextEvent", "(", "EventLog", "<", "LeadershipEventListener", "<", "String", ">", ",", "LeadershipEvent", "<", "String", ">", ">", "eventLog", ",", "String", "name", ",", "String", "id", ",", "AsyncResponse", "response", ")", "{", "eventLog", ".", "nextEvent", "(", ")", ".", "whenComplete", "(", "(", "event", ",", "error", ")", "->", "{", "if", "(", "error", "==", "null", ")", "{", "if", "(", "event", ".", "newLeadership", "(", ")", ".", "leader", "(", ")", "!=", "null", "&&", "event", ".", "newLeadership", "(", ")", ".", "leader", "(", ")", ".", "id", "(", ")", ".", "equals", "(", "id", ")", ")", "{", "response", ".", "resume", "(", "Response", ".", "ok", "(", "new", "LeadershipResponse", "(", "event", ".", "newLeadership", "(", ")", ")", ")", ".", "build", "(", ")", ")", ";", "}", "else", "if", "(", "event", ".", "newLeadership", "(", ")", ".", "candidates", "(", ")", ".", "stream", "(", ")", ".", "noneMatch", "(", "c", "->", "c", ".", "equals", "(", "id", ")", ")", ")", "{", "getPrimitive", "(", "name", ")", ".", "thenCompose", "(", "election", "->", "election", ".", "removeListener", "(", "eventLog", ".", "listener", "(", ")", ")", ")", ".", "whenComplete", "(", "(", "removeResult", ",", "removeError", ")", "->", "{", "response", ".", "resume", "(", "Response", ".", "status", "(", "Status", ".", "NOT_FOUND", ")", ".", "build", "(", ")", ")", ";", "}", ")", ";", "}", "}", "else", "{", "response", ".", "resume", "(", "Response", ".", "status", "(", "Status", ".", "NOT_FOUND", ")", ".", "build", "(", ")", ")", ";", "}", "}", ")", ";", "}" ]
Recursively consumes events from the given event log until the next event for the given ID is located.
[ "Recursively", "consumes", "events", "from", "the", "given", "event", "log", "until", "the", "next", "event", "for", "the", "given", "ID", "is", "located", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/rest/src/main/java/io/atomix/rest/resources/LeaderElectionResource.java#L123-L141
27,422
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/impl/DefaultRaftMetadataClient.java
DefaultRaftMetadataClient.getMetadata
private CompletableFuture<MetadataResponse> getMetadata() { CompletableFuture<MetadataResponse> future = new CompletableFuture<>(); connection.metadata(MetadataRequest.builder().build()).whenComplete((response, error) -> { if (error == null) { if (response.status() == RaftResponse.Status.OK) { future.complete(response); } else { future.completeExceptionally(response.error().createException()); } } else { future.completeExceptionally(error); } }); return future; }
java
private CompletableFuture<MetadataResponse> getMetadata() { CompletableFuture<MetadataResponse> future = new CompletableFuture<>(); connection.metadata(MetadataRequest.builder().build()).whenComplete((response, error) -> { if (error == null) { if (response.status() == RaftResponse.Status.OK) { future.complete(response); } else { future.completeExceptionally(response.error().createException()); } } else { future.completeExceptionally(error); } }); return future; }
[ "private", "CompletableFuture", "<", "MetadataResponse", ">", "getMetadata", "(", ")", "{", "CompletableFuture", "<", "MetadataResponse", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "connection", ".", "metadata", "(", "MetadataRequest", ".", "builder", "(", ")", ".", "build", "(", ")", ")", ".", "whenComplete", "(", "(", "response", ",", "error", ")", "->", "{", "if", "(", "error", "==", "null", ")", "{", "if", "(", "response", ".", "status", "(", ")", "==", "RaftResponse", ".", "Status", ".", "OK", ")", "{", "future", ".", "complete", "(", "response", ")", ";", "}", "else", "{", "future", ".", "completeExceptionally", "(", "response", ".", "error", "(", ")", ".", "createException", "(", ")", ")", ";", "}", "}", "else", "{", "future", ".", "completeExceptionally", "(", "error", ")", ";", "}", "}", ")", ";", "return", "future", ";", "}" ]
Requests metadata from the cluster. @return A completable future to be completed with cluster metadata.
[ "Requests", "metadata", "from", "the", "cluster", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/impl/DefaultRaftMetadataClient.java#L73-L87
27,423
atomix/atomix
cluster/src/main/java/io/atomix/cluster/impl/DefaultClusterMembershipService.java
DefaultClusterMembershipService.handleMembershipEvent
private void handleMembershipEvent(GroupMembershipEvent event) { post(new ClusterMembershipEvent(ClusterMembershipEvent.Type.valueOf(event.type().name()), event.member())); }
java
private void handleMembershipEvent(GroupMembershipEvent event) { post(new ClusterMembershipEvent(ClusterMembershipEvent.Type.valueOf(event.type().name()), event.member())); }
[ "private", "void", "handleMembershipEvent", "(", "GroupMembershipEvent", "event", ")", "{", "post", "(", "new", "ClusterMembershipEvent", "(", "ClusterMembershipEvent", ".", "Type", ".", "valueOf", "(", "event", ".", "type", "(", ")", ".", "name", "(", ")", ")", ",", "event", ".", "member", "(", ")", ")", ")", ";", "}" ]
Handles a group membership event.
[ "Handles", "a", "group", "membership", "event", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/impl/DefaultClusterMembershipService.java#L96-L98
27,424
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.builder
public static AtomixClusterBuilder builder(String config, ClassLoader classLoader) { return new AtomixClusterBuilder(config(withDefaultResources(config), classLoader)); }
java
public static AtomixClusterBuilder builder(String config, ClassLoader classLoader) { return new AtomixClusterBuilder(config(withDefaultResources(config), classLoader)); }
[ "public", "static", "AtomixClusterBuilder", "builder", "(", "String", "config", ",", "ClassLoader", "classLoader", ")", "{", "return", "new", "AtomixClusterBuilder", "(", "config", "(", "withDefaultResources", "(", "config", ")", ",", "classLoader", ")", ")", ";", "}" ]
Returns a new Atomix builder. @param config the Atomix configuration @param classLoader the class loader @return a new Atomix builder
[ "Returns", "a", "new", "Atomix", "builder", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L151-L153
27,425
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.loadConfig
private static ClusterConfig loadConfig(File config, ClassLoader classLoader) { return new ConfigMapper(classLoader).loadResources(ClusterConfig.class, config.getAbsolutePath()); }
java
private static ClusterConfig loadConfig(File config, ClassLoader classLoader) { return new ConfigMapper(classLoader).loadResources(ClusterConfig.class, config.getAbsolutePath()); }
[ "private", "static", "ClusterConfig", "loadConfig", "(", "File", "config", ",", "ClassLoader", "classLoader", ")", "{", "return", "new", "ConfigMapper", "(", "classLoader", ")", ".", "loadResources", "(", "ClusterConfig", ".", "class", ",", "config", ".", "getAbsolutePath", "(", ")", ")", ";", "}" ]
Loads a configuration from the given file.
[ "Loads", "a", "configuration", "from", "the", "given", "file", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L360-L362
27,426
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.buildMessagingService
protected static ManagedMessagingService buildMessagingService(ClusterConfig config) { return new NettyMessagingService( config.getClusterId(), config.getNodeConfig().getAddress(), config.getMessagingConfig()); }
java
protected static ManagedMessagingService buildMessagingService(ClusterConfig config) { return new NettyMessagingService( config.getClusterId(), config.getNodeConfig().getAddress(), config.getMessagingConfig()); }
[ "protected", "static", "ManagedMessagingService", "buildMessagingService", "(", "ClusterConfig", "config", ")", "{", "return", "new", "NettyMessagingService", "(", "config", ".", "getClusterId", "(", ")", ",", "config", ".", "getNodeConfig", "(", ")", ".", "getAddress", "(", ")", ",", "config", ".", "getMessagingConfig", "(", ")", ")", ";", "}" ]
Builds a default messaging service.
[ "Builds", "a", "default", "messaging", "service", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L367-L372
27,427
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.buildUnicastService
protected static ManagedUnicastService buildUnicastService(ClusterConfig config) { return new NettyUnicastService(config.getNodeConfig().getAddress(), config.getMessagingConfig()); }
java
protected static ManagedUnicastService buildUnicastService(ClusterConfig config) { return new NettyUnicastService(config.getNodeConfig().getAddress(), config.getMessagingConfig()); }
[ "protected", "static", "ManagedUnicastService", "buildUnicastService", "(", "ClusterConfig", "config", ")", "{", "return", "new", "NettyUnicastService", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getAddress", "(", ")", ",", "config", ".", "getMessagingConfig", "(", ")", ")", ";", "}" ]
Builds a default unicast service.
[ "Builds", "a", "default", "unicast", "service", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L377-L379
27,428
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.buildBroadcastService
protected static ManagedBroadcastService buildBroadcastService(ClusterConfig config) { return NettyBroadcastService.builder() .withLocalAddress(config.getNodeConfig().getAddress()) .withGroupAddress(new Address( config.getMulticastConfig().getGroup().getHostAddress(), config.getMulticastConfig().getPort(), config.getMulticastConfig().getGroup())) .withEnabled(config.getMulticastConfig().isEnabled()) .build(); }
java
protected static ManagedBroadcastService buildBroadcastService(ClusterConfig config) { return NettyBroadcastService.builder() .withLocalAddress(config.getNodeConfig().getAddress()) .withGroupAddress(new Address( config.getMulticastConfig().getGroup().getHostAddress(), config.getMulticastConfig().getPort(), config.getMulticastConfig().getGroup())) .withEnabled(config.getMulticastConfig().isEnabled()) .build(); }
[ "protected", "static", "ManagedBroadcastService", "buildBroadcastService", "(", "ClusterConfig", "config", ")", "{", "return", "NettyBroadcastService", ".", "builder", "(", ")", ".", "withLocalAddress", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getAddress", "(", ")", ")", ".", "withGroupAddress", "(", "new", "Address", "(", "config", ".", "getMulticastConfig", "(", ")", ".", "getGroup", "(", ")", ".", "getHostAddress", "(", ")", ",", "config", ".", "getMulticastConfig", "(", ")", ".", "getPort", "(", ")", ",", "config", ".", "getMulticastConfig", "(", ")", ".", "getGroup", "(", ")", ")", ")", ".", "withEnabled", "(", "config", ".", "getMulticastConfig", "(", ")", ".", "isEnabled", "(", ")", ")", ".", "build", "(", ")", ";", "}" ]
Builds a default broadcast service.
[ "Builds", "a", "default", "broadcast", "service", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L384-L393
27,429
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.buildLocationProvider
@SuppressWarnings("unchecked") protected static NodeDiscoveryProvider buildLocationProvider(ClusterConfig config) { NodeDiscoveryConfig discoveryProviderConfig = config.getDiscoveryConfig(); if (discoveryProviderConfig != null) { return discoveryProviderConfig.getType().newProvider(discoveryProviderConfig); } if (config.getMulticastConfig().isEnabled()) { return new MulticastDiscoveryProvider(new MulticastDiscoveryConfig()); } else { return new BootstrapDiscoveryProvider(Collections.emptyList()); } }
java
@SuppressWarnings("unchecked") protected static NodeDiscoveryProvider buildLocationProvider(ClusterConfig config) { NodeDiscoveryConfig discoveryProviderConfig = config.getDiscoveryConfig(); if (discoveryProviderConfig != null) { return discoveryProviderConfig.getType().newProvider(discoveryProviderConfig); } if (config.getMulticastConfig().isEnabled()) { return new MulticastDiscoveryProvider(new MulticastDiscoveryConfig()); } else { return new BootstrapDiscoveryProvider(Collections.emptyList()); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "static", "NodeDiscoveryProvider", "buildLocationProvider", "(", "ClusterConfig", "config", ")", "{", "NodeDiscoveryConfig", "discoveryProviderConfig", "=", "config", ".", "getDiscoveryConfig", "(", ")", ";", "if", "(", "discoveryProviderConfig", "!=", "null", ")", "{", "return", "discoveryProviderConfig", ".", "getType", "(", ")", ".", "newProvider", "(", "discoveryProviderConfig", ")", ";", "}", "if", "(", "config", ".", "getMulticastConfig", "(", ")", ".", "isEnabled", "(", ")", ")", "{", "return", "new", "MulticastDiscoveryProvider", "(", "new", "MulticastDiscoveryConfig", "(", ")", ")", ";", "}", "else", "{", "return", "new", "BootstrapDiscoveryProvider", "(", "Collections", ".", "emptyList", "(", ")", ")", ";", "}", "}" ]
Builds a member location provider.
[ "Builds", "a", "member", "location", "provider", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L398-L409
27,430
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.buildMembershipProtocol
@SuppressWarnings("unchecked") protected static GroupMembershipProtocol buildMembershipProtocol(ClusterConfig config) { return config.getProtocolConfig().getType().newProtocol(config.getProtocolConfig()); }
java
@SuppressWarnings("unchecked") protected static GroupMembershipProtocol buildMembershipProtocol(ClusterConfig config) { return config.getProtocolConfig().getType().newProtocol(config.getProtocolConfig()); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "static", "GroupMembershipProtocol", "buildMembershipProtocol", "(", "ClusterConfig", "config", ")", "{", "return", "config", ".", "getProtocolConfig", "(", ")", ".", "getType", "(", ")", ".", "newProtocol", "(", "config", ".", "getProtocolConfig", "(", ")", ")", ";", "}" ]
Builds the group membership protocol.
[ "Builds", "the", "group", "membership", "protocol", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L414-L417
27,431
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.buildClusterMembershipService
protected static ManagedClusterMembershipService buildClusterMembershipService( ClusterConfig config, BootstrapService bootstrapService, NodeDiscoveryProvider discoveryProvider, GroupMembershipProtocol membershipProtocol, Version version) { // If the local node has not be configured, create a default node. Member localMember = Member.builder() .withId(config.getNodeConfig().getId()) .withAddress(config.getNodeConfig().getAddress()) .withHostId(config.getNodeConfig().getHostId()) .withRackId(config.getNodeConfig().getRackId()) .withZoneId(config.getNodeConfig().getZoneId()) .withProperties(config.getNodeConfig().getProperties()) .build(); return new DefaultClusterMembershipService( localMember, version, new DefaultNodeDiscoveryService(bootstrapService, localMember, discoveryProvider), bootstrapService, membershipProtocol); }
java
protected static ManagedClusterMembershipService buildClusterMembershipService( ClusterConfig config, BootstrapService bootstrapService, NodeDiscoveryProvider discoveryProvider, GroupMembershipProtocol membershipProtocol, Version version) { // If the local node has not be configured, create a default node. Member localMember = Member.builder() .withId(config.getNodeConfig().getId()) .withAddress(config.getNodeConfig().getAddress()) .withHostId(config.getNodeConfig().getHostId()) .withRackId(config.getNodeConfig().getRackId()) .withZoneId(config.getNodeConfig().getZoneId()) .withProperties(config.getNodeConfig().getProperties()) .build(); return new DefaultClusterMembershipService( localMember, version, new DefaultNodeDiscoveryService(bootstrapService, localMember, discoveryProvider), bootstrapService, membershipProtocol); }
[ "protected", "static", "ManagedClusterMembershipService", "buildClusterMembershipService", "(", "ClusterConfig", "config", ",", "BootstrapService", "bootstrapService", ",", "NodeDiscoveryProvider", "discoveryProvider", ",", "GroupMembershipProtocol", "membershipProtocol", ",", "Version", "version", ")", "{", "// If the local node has not be configured, create a default node.", "Member", "localMember", "=", "Member", ".", "builder", "(", ")", ".", "withId", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getId", "(", ")", ")", ".", "withAddress", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getAddress", "(", ")", ")", ".", "withHostId", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getHostId", "(", ")", ")", ".", "withRackId", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getRackId", "(", ")", ")", ".", "withZoneId", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getZoneId", "(", ")", ")", ".", "withProperties", "(", "config", ".", "getNodeConfig", "(", ")", ".", "getProperties", "(", ")", ")", ".", "build", "(", ")", ";", "return", "new", "DefaultClusterMembershipService", "(", "localMember", ",", "version", ",", "new", "DefaultNodeDiscoveryService", "(", "bootstrapService", ",", "localMember", ",", "discoveryProvider", ")", ",", "bootstrapService", ",", "membershipProtocol", ")", ";", "}" ]
Builds a cluster service.
[ "Builds", "a", "cluster", "service", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L422-L443
27,432
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixCluster.java
AtomixCluster.buildClusterMessagingService
protected static ManagedClusterCommunicationService buildClusterMessagingService( ClusterMembershipService membershipService, MessagingService messagingService, UnicastService unicastService) { return new DefaultClusterCommunicationService(membershipService, messagingService, unicastService); }
java
protected static ManagedClusterCommunicationService buildClusterMessagingService( ClusterMembershipService membershipService, MessagingService messagingService, UnicastService unicastService) { return new DefaultClusterCommunicationService(membershipService, messagingService, unicastService); }
[ "protected", "static", "ManagedClusterCommunicationService", "buildClusterMessagingService", "(", "ClusterMembershipService", "membershipService", ",", "MessagingService", "messagingService", ",", "UnicastService", "unicastService", ")", "{", "return", "new", "DefaultClusterCommunicationService", "(", "membershipService", ",", "messagingService", ",", "unicastService", ")", ";", "}" ]
Builds a cluster messaging service.
[ "Builds", "a", "cluster", "messaging", "service", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixCluster.java#L448-L451
27,433
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.open
public CompletableFuture<Void> open() { return primaryElection.getTerm() .thenAccept(this::changeRole) .thenRun(() -> service.init(this)); }
java
public CompletableFuture<Void> open() { return primaryElection.getTerm() .thenAccept(this::changeRole) .thenRun(() -> service.init(this)); }
[ "public", "CompletableFuture", "<", "Void", ">", "open", "(", ")", "{", "return", "primaryElection", ".", "getTerm", "(", ")", ".", "thenAccept", "(", "this", "::", "changeRole", ")", ".", "thenRun", "(", "(", ")", "->", "service", ".", "init", "(", "this", ")", ")", ";", "}" ]
Opens the service context. @return a future to be completed once the service context has been opened
[ "Opens", "the", "service", "context", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L154-L158
27,434
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.setTimestamp
public long setTimestamp(long timestamp) { this.currentTimestamp = timestamp; service.tick(WallClockTimestamp.from(timestamp)); return currentTimestamp; }
java
public long setTimestamp(long timestamp) { this.currentTimestamp = timestamp; service.tick(WallClockTimestamp.from(timestamp)); return currentTimestamp; }
[ "public", "long", "setTimestamp", "(", "long", "timestamp", ")", "{", "this", ".", "currentTimestamp", "=", "timestamp", ";", "service", ".", "tick", "(", "WallClockTimestamp", ".", "from", "(", "timestamp", ")", ")", ";", "return", "currentTimestamp", ";", "}" ]
Sets the current timestamp. @param timestamp the updated timestamp @return the current timestamp
[ "Sets", "the", "current", "timestamp", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L247-L251
27,435
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.nextIndex
public boolean nextIndex(long index) { if (operationIndex + 1 == index) { currentOperation = OperationType.COMMAND; operationIndex++; return true; } return false; }
java
public boolean nextIndex(long index) { if (operationIndex + 1 == index) { currentOperation = OperationType.COMMAND; operationIndex++; return true; } return false; }
[ "public", "boolean", "nextIndex", "(", "long", "index", ")", "{", "if", "(", "operationIndex", "+", "1", "==", "index", ")", "{", "currentOperation", "=", "OperationType", ".", "COMMAND", ";", "operationIndex", "++", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Increments the current index and returns true if the given index is the next index. @param index the index to which to increment the current index @return indicates whether the current index was successfully incremented
[ "Increments", "the", "current", "index", "and", "returns", "true", "if", "the", "given", "index", "is", "the", "next", "index", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L289-L296
27,436
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.resetIndex
public void resetIndex(long index, long timestamp) { currentOperation = OperationType.COMMAND; operationIndex = index; currentIndex = index; currentTimestamp = timestamp; setCommitIndex(index); service.tick(new WallClockTimestamp(currentTimestamp)); }
java
public void resetIndex(long index, long timestamp) { currentOperation = OperationType.COMMAND; operationIndex = index; currentIndex = index; currentTimestamp = timestamp; setCommitIndex(index); service.tick(new WallClockTimestamp(currentTimestamp)); }
[ "public", "void", "resetIndex", "(", "long", "index", ",", "long", "timestamp", ")", "{", "currentOperation", "=", "OperationType", ".", "COMMAND", ";", "operationIndex", "=", "index", ";", "currentIndex", "=", "index", ";", "currentTimestamp", "=", "timestamp", ";", "setCommitIndex", "(", "index", ")", ";", "service", ".", "tick", "(", "new", "WallClockTimestamp", "(", "currentTimestamp", ")", ")", ";", "}" ]
Resets the current index to the given index and timestamp. @param index the index to which to reset the current index @param timestamp the timestamp to which to reset the current timestamp
[ "Resets", "the", "current", "index", "to", "the", "given", "index", "and", "timestamp", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L304-L311
27,437
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.createSession
public PrimaryBackupSession createSession(long sessionId, MemberId memberId) { PrimaryBackupSession session = new PrimaryBackupSession(SessionId.from(sessionId), memberId, service.serializer(), this); if (sessions.putIfAbsent(sessionId, session) == null) { service.register(session); } return session; }
java
public PrimaryBackupSession createSession(long sessionId, MemberId memberId) { PrimaryBackupSession session = new PrimaryBackupSession(SessionId.from(sessionId), memberId, service.serializer(), this); if (sessions.putIfAbsent(sessionId, session) == null) { service.register(session); } return session; }
[ "public", "PrimaryBackupSession", "createSession", "(", "long", "sessionId", ",", "MemberId", "memberId", ")", "{", "PrimaryBackupSession", "session", "=", "new", "PrimaryBackupSession", "(", "SessionId", ".", "from", "(", "sessionId", ")", ",", "memberId", ",", "service", ".", "serializer", "(", ")", ",", "this", ")", ";", "if", "(", "sessions", ".", "putIfAbsent", "(", "sessionId", ",", "session", ")", "==", "null", ")", "{", "service", ".", "register", "(", "session", ")", ";", "}", "return", "session", ";", "}" ]
Creates a service session. @param sessionId the session to create @param memberId the owning node ID @return the service session
[ "Creates", "a", "service", "session", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L519-L525
27,438
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.getOrCreateSession
public PrimaryBackupSession getOrCreateSession(long sessionId, MemberId memberId) { PrimaryBackupSession session = sessions.get(sessionId); if (session == null) { session = createSession(sessionId, memberId); } return session; }
java
public PrimaryBackupSession getOrCreateSession(long sessionId, MemberId memberId) { PrimaryBackupSession session = sessions.get(sessionId); if (session == null) { session = createSession(sessionId, memberId); } return session; }
[ "public", "PrimaryBackupSession", "getOrCreateSession", "(", "long", "sessionId", ",", "MemberId", "memberId", ")", "{", "PrimaryBackupSession", "session", "=", "sessions", ".", "get", "(", "sessionId", ")", ";", "if", "(", "session", "==", "null", ")", "{", "session", "=", "createSession", "(", "sessionId", ",", "memberId", ")", ";", "}", "return", "session", ";", "}" ]
Gets or creates a service session. @param sessionId the session to create @param memberId the owning node ID @return the service session
[ "Gets", "or", "creates", "a", "service", "session", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L534-L540
27,439
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.expireSession
public void expireSession(long sessionId) { PrimaryBackupSession session = sessions.remove(sessionId); if (session != null) { log.debug("Expiring session {}", session.sessionId()); session.expire(); service.expire(session.sessionId()); } }
java
public void expireSession(long sessionId) { PrimaryBackupSession session = sessions.remove(sessionId); if (session != null) { log.debug("Expiring session {}", session.sessionId()); session.expire(); service.expire(session.sessionId()); } }
[ "public", "void", "expireSession", "(", "long", "sessionId", ")", "{", "PrimaryBackupSession", "session", "=", "sessions", ".", "remove", "(", "sessionId", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "log", ".", "debug", "(", "\"Expiring session {}\"", ",", "session", ".", "sessionId", "(", ")", ")", ";", "session", ".", "expire", "(", ")", ";", "service", ".", "expire", "(", "session", ".", "sessionId", "(", ")", ")", ";", "}", "}" ]
Expires the session with the given ID. @param sessionId the session ID
[ "Expires", "the", "session", "with", "the", "given", "ID", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L547-L554
27,440
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.closeSession
public void closeSession(long sessionId) { PrimaryBackupSession session = sessions.remove(sessionId); if (session != null) { log.debug("Closing session {}", session.sessionId()); session.close(); service.close(session.sessionId()); } }
java
public void closeSession(long sessionId) { PrimaryBackupSession session = sessions.remove(sessionId); if (session != null) { log.debug("Closing session {}", session.sessionId()); session.close(); service.close(session.sessionId()); } }
[ "public", "void", "closeSession", "(", "long", "sessionId", ")", "{", "PrimaryBackupSession", "session", "=", "sessions", ".", "remove", "(", "sessionId", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "log", ".", "debug", "(", "\"Closing session {}\"", ",", "session", ".", "sessionId", "(", ")", ")", ";", "session", ".", "close", "(", ")", ";", "service", ".", "close", "(", "session", ".", "sessionId", "(", ")", ")", ";", "}", "}" ]
Closes the session with the given ID. @param sessionId the session ID
[ "Closes", "the", "session", "with", "the", "given", "ID", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L561-L568
27,441
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java
PrimaryBackupServiceContext.close
public CompletableFuture<Void> close() { CompletableFuture<Void> future = new CompletableFuture<>(); threadContext.execute(() -> { try { clusterMembershipService.removeListener(membershipEventListener); primaryElection.removeListener(primaryElectionListener); role.close(); } finally { future.complete(null); } }); return future.thenRunAsync(() -> threadContext.close()); }
java
public CompletableFuture<Void> close() { CompletableFuture<Void> future = new CompletableFuture<>(); threadContext.execute(() -> { try { clusterMembershipService.removeListener(membershipEventListener); primaryElection.removeListener(primaryElectionListener); role.close(); } finally { future.complete(null); } }); return future.thenRunAsync(() -> threadContext.close()); }
[ "public", "CompletableFuture", "<", "Void", ">", "close", "(", ")", "{", "CompletableFuture", "<", "Void", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "threadContext", ".", "execute", "(", "(", ")", "->", "{", "try", "{", "clusterMembershipService", ".", "removeListener", "(", "membershipEventListener", ")", ";", "primaryElection", ".", "removeListener", "(", "primaryElectionListener", ")", ";", "role", ".", "close", "(", ")", ";", "}", "finally", "{", "future", ".", "complete", "(", "null", ")", ";", "}", "}", ")", ";", "return", "future", ".", "thenRunAsync", "(", "(", ")", "->", "threadContext", ".", "close", "(", ")", ")", ";", "}" ]
Closes the service.
[ "Closes", "the", "service", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/service/impl/PrimaryBackupServiceContext.java#L634-L646
27,442
atomix/atomix
protocols/log/src/main/java/io/atomix/protocols/log/roles/LogServerRole.java
LogServerRole.consume
public CompletableFuture<ConsumeResponse> consume(ConsumeRequest request) { logRequest(request); return CompletableFuture.completedFuture(logResponse(ConsumeResponse.error())); }
java
public CompletableFuture<ConsumeResponse> consume(ConsumeRequest request) { logRequest(request); return CompletableFuture.completedFuture(logResponse(ConsumeResponse.error())); }
[ "public", "CompletableFuture", "<", "ConsumeResponse", ">", "consume", "(", "ConsumeRequest", "request", ")", "{", "logRequest", "(", "request", ")", ";", "return", "CompletableFuture", ".", "completedFuture", "(", "logResponse", "(", "ConsumeResponse", ".", "error", "(", ")", ")", ")", ";", "}" ]
Handles a consume request. @param request the consume request @return future to be completed with the consume response
[ "Handles", "a", "consume", "request", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/log/src/main/java/io/atomix/protocols/log/roles/LogServerRole.java#L96-L99
27,443
atomix/atomix
primitive/src/main/java/io/atomix/primitive/partition/impl/DefaultPartitionGroupMembershipService.java
DefaultPartitionGroupMembershipService.handleMembershipChange
private void handleMembershipChange(ClusterMembershipEvent event) { if (event.type() == ClusterMembershipEvent.Type.MEMBER_ADDED) { bootstrap(event.subject()); } else if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) { threadContext.execute(() -> { PartitionGroupMembership systemGroup = this.systemGroup; if (systemGroup != null && systemGroup.members().contains(event.subject().id())) { Set<MemberId> newMembers = Sets.newHashSet(systemGroup.members()); newMembers.remove(event.subject().id()); PartitionGroupMembership newMembership = new PartitionGroupMembership(systemGroup.group(), systemGroup.config(), ImmutableSet.copyOf(newMembers), true); this.systemGroup = newMembership; post(new PartitionGroupMembershipEvent(MEMBERS_CHANGED, newMembership)); } groups.values().forEach(group -> { if (group.members().contains(event.subject().id())) { Set<MemberId> newMembers = Sets.newHashSet(group.members()); newMembers.remove(event.subject().id()); PartitionGroupMembership newMembership = new PartitionGroupMembership(group.group(), group.config(), ImmutableSet.copyOf(newMembers), false); groups.put(group.group(), newMembership); post(new PartitionGroupMembershipEvent(MEMBERS_CHANGED, newMembership)); } }); }); } }
java
private void handleMembershipChange(ClusterMembershipEvent event) { if (event.type() == ClusterMembershipEvent.Type.MEMBER_ADDED) { bootstrap(event.subject()); } else if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) { threadContext.execute(() -> { PartitionGroupMembership systemGroup = this.systemGroup; if (systemGroup != null && systemGroup.members().contains(event.subject().id())) { Set<MemberId> newMembers = Sets.newHashSet(systemGroup.members()); newMembers.remove(event.subject().id()); PartitionGroupMembership newMembership = new PartitionGroupMembership(systemGroup.group(), systemGroup.config(), ImmutableSet.copyOf(newMembers), true); this.systemGroup = newMembership; post(new PartitionGroupMembershipEvent(MEMBERS_CHANGED, newMembership)); } groups.values().forEach(group -> { if (group.members().contains(event.subject().id())) { Set<MemberId> newMembers = Sets.newHashSet(group.members()); newMembers.remove(event.subject().id()); PartitionGroupMembership newMembership = new PartitionGroupMembership(group.group(), group.config(), ImmutableSet.copyOf(newMembers), false); groups.put(group.group(), newMembership); post(new PartitionGroupMembershipEvent(MEMBERS_CHANGED, newMembership)); } }); }); } }
[ "private", "void", "handleMembershipChange", "(", "ClusterMembershipEvent", "event", ")", "{", "if", "(", "event", ".", "type", "(", ")", "==", "ClusterMembershipEvent", ".", "Type", ".", "MEMBER_ADDED", ")", "{", "bootstrap", "(", "event", ".", "subject", "(", ")", ")", ";", "}", "else", "if", "(", "event", ".", "type", "(", ")", "==", "ClusterMembershipEvent", ".", "Type", ".", "MEMBER_REMOVED", ")", "{", "threadContext", ".", "execute", "(", "(", ")", "->", "{", "PartitionGroupMembership", "systemGroup", "=", "this", ".", "systemGroup", ";", "if", "(", "systemGroup", "!=", "null", "&&", "systemGroup", ".", "members", "(", ")", ".", "contains", "(", "event", ".", "subject", "(", ")", ".", "id", "(", ")", ")", ")", "{", "Set", "<", "MemberId", ">", "newMembers", "=", "Sets", ".", "newHashSet", "(", "systemGroup", ".", "members", "(", ")", ")", ";", "newMembers", ".", "remove", "(", "event", ".", "subject", "(", ")", ".", "id", "(", ")", ")", ";", "PartitionGroupMembership", "newMembership", "=", "new", "PartitionGroupMembership", "(", "systemGroup", ".", "group", "(", ")", ",", "systemGroup", ".", "config", "(", ")", ",", "ImmutableSet", ".", "copyOf", "(", "newMembers", ")", ",", "true", ")", ";", "this", ".", "systemGroup", "=", "newMembership", ";", "post", "(", "new", "PartitionGroupMembershipEvent", "(", "MEMBERS_CHANGED", ",", "newMembership", ")", ")", ";", "}", "groups", ".", "values", "(", ")", ".", "forEach", "(", "group", "->", "{", "if", "(", "group", ".", "members", "(", ")", ".", "contains", "(", "event", ".", "subject", "(", ")", ".", "id", "(", ")", ")", ")", "{", "Set", "<", "MemberId", ">", "newMembers", "=", "Sets", ".", "newHashSet", "(", "group", ".", "members", "(", ")", ")", ";", "newMembers", ".", "remove", "(", "event", ".", "subject", "(", ")", ".", "id", "(", ")", ")", ";", "PartitionGroupMembership", "newMembership", "=", "new", "PartitionGroupMembership", "(", "group", ".", "group", "(", ")", ",", "group", ".", "config", "(", ")", ",", "ImmutableSet", ".", "copyOf", "(", "newMembers", ")", ",", "false", ")", ";", "groups", ".", "put", "(", "group", ".", "group", "(", ")", ",", "newMembership", ")", ";", "post", "(", "new", "PartitionGroupMembershipEvent", "(", "MEMBERS_CHANGED", ",", "newMembership", ")", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}" ]
Handles a cluster membership change.
[ "Handles", "a", "cluster", "membership", "change", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/DefaultPartitionGroupMembershipService.java#L146-L171
27,444
atomix/atomix
primitive/src/main/java/io/atomix/primitive/partition/impl/DefaultPartitionGroupMembershipService.java
DefaultPartitionGroupMembershipService.bootstrap
private CompletableFuture<Void> bootstrap(int attempt, CompletableFuture<Void> future) { Futures.allOf(membershipService.getMembers().stream() .filter(node -> !node.id().equals(membershipService.getLocalMember().id())) .map(node -> bootstrap(node)) .collect(Collectors.toList())) .whenComplete((result, error) -> { if (error == null) { if (systemGroup == null) { LOGGER.warn("Failed to locate management group via bootstrap nodes. Please ensure partition " + "groups are configured either locally or remotely and the node is able to reach partition group members."); threadContext.schedule(Duration.ofSeconds(FIBONACCI_NUMBERS[Math.min(attempt, 4)]), () -> bootstrap(attempt + 1, future)); } else if (groups.isEmpty() && attempt < MAX_PARTITION_GROUP_ATTEMPTS) { LOGGER.warn("Failed to locate partition group(s) via bootstrap nodes. Please ensure partition " + "groups are configured either locally or remotely and the node is able to reach partition group members."); threadContext.schedule(Duration.ofSeconds(FIBONACCI_NUMBERS[Math.min(attempt, 4)]), () -> bootstrap(attempt + 1, future)); } else { future.complete(null); } } else { future.completeExceptionally(error); } }); return future; }
java
private CompletableFuture<Void> bootstrap(int attempt, CompletableFuture<Void> future) { Futures.allOf(membershipService.getMembers().stream() .filter(node -> !node.id().equals(membershipService.getLocalMember().id())) .map(node -> bootstrap(node)) .collect(Collectors.toList())) .whenComplete((result, error) -> { if (error == null) { if (systemGroup == null) { LOGGER.warn("Failed to locate management group via bootstrap nodes. Please ensure partition " + "groups are configured either locally or remotely and the node is able to reach partition group members."); threadContext.schedule(Duration.ofSeconds(FIBONACCI_NUMBERS[Math.min(attempt, 4)]), () -> bootstrap(attempt + 1, future)); } else if (groups.isEmpty() && attempt < MAX_PARTITION_GROUP_ATTEMPTS) { LOGGER.warn("Failed to locate partition group(s) via bootstrap nodes. Please ensure partition " + "groups are configured either locally or remotely and the node is able to reach partition group members."); threadContext.schedule(Duration.ofSeconds(FIBONACCI_NUMBERS[Math.min(attempt, 4)]), () -> bootstrap(attempt + 1, future)); } else { future.complete(null); } } else { future.completeExceptionally(error); } }); return future; }
[ "private", "CompletableFuture", "<", "Void", ">", "bootstrap", "(", "int", "attempt", ",", "CompletableFuture", "<", "Void", ">", "future", ")", "{", "Futures", ".", "allOf", "(", "membershipService", ".", "getMembers", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "node", "->", "!", "node", ".", "id", "(", ")", ".", "equals", "(", "membershipService", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ")", ")", ".", "map", "(", "node", "->", "bootstrap", "(", "node", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ".", "whenComplete", "(", "(", "result", ",", "error", ")", "->", "{", "if", "(", "error", "==", "null", ")", "{", "if", "(", "systemGroup", "==", "null", ")", "{", "LOGGER", ".", "warn", "(", "\"Failed to locate management group via bootstrap nodes. Please ensure partition \"", "+", "\"groups are configured either locally or remotely and the node is able to reach partition group members.\"", ")", ";", "threadContext", ".", "schedule", "(", "Duration", ".", "ofSeconds", "(", "FIBONACCI_NUMBERS", "[", "Math", ".", "min", "(", "attempt", ",", "4", ")", "]", ")", ",", "(", ")", "->", "bootstrap", "(", "attempt", "+", "1", ",", "future", ")", ")", ";", "}", "else", "if", "(", "groups", ".", "isEmpty", "(", ")", "&&", "attempt", "<", "MAX_PARTITION_GROUP_ATTEMPTS", ")", "{", "LOGGER", ".", "warn", "(", "\"Failed to locate partition group(s) via bootstrap nodes. Please ensure partition \"", "+", "\"groups are configured either locally or remotely and the node is able to reach partition group members.\"", ")", ";", "threadContext", ".", "schedule", "(", "Duration", ".", "ofSeconds", "(", "FIBONACCI_NUMBERS", "[", "Math", ".", "min", "(", "attempt", ",", "4", ")", "]", ")", ",", "(", ")", "->", "bootstrap", "(", "attempt", "+", "1", ",", "future", ")", ")", ";", "}", "else", "{", "future", ".", "complete", "(", "null", ")", ";", "}", "}", "else", "{", "future", ".", "completeExceptionally", "(", "error", ")", ";", "}", "}", ")", ";", "return", "future", ";", "}" ]
Recursively bootstraps the service, retrying if necessary until a system partition group is found.
[ "Recursively", "bootstraps", "the", "service", "retrying", "if", "necessary", "until", "a", "system", "partition", "group", "is", "found", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/DefaultPartitionGroupMembershipService.java#L183-L206
27,445
atomix/atomix
primitive/src/main/java/io/atomix/primitive/partition/impl/DefaultPartitionGroupMembershipService.java
DefaultPartitionGroupMembershipService.bootstrap
@SuppressWarnings("unchecked") private CompletableFuture<Void> bootstrap(Member member, CompletableFuture<Void> future) { LOGGER.debug("{} - Bootstrapping from member {}", membershipService.getLocalMember().id(), member); messagingService.<PartitionGroupInfo, PartitionGroupInfo>send( BOOTSTRAP_SUBJECT, new PartitionGroupInfo(membershipService.getLocalMember().id(), systemGroup, Lists.newArrayList(groups.values())), serializer::encode, serializer::decode, member.id()) .whenCompleteAsync((info, error) -> { if (error == null) { try { updatePartitionGroups(info); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); } } else { error = Throwables.getRootCause(error); if (error instanceof MessagingException.NoRemoteHandler || error instanceof TimeoutException) { threadContext.schedule(Duration.ofSeconds(1), () -> bootstrap(member, future)); } else { LOGGER.debug("{} - Failed to bootstrap from member {}", membershipService.getLocalMember().id(), member, error); future.complete(null); } } }, threadContext); return future; }
java
@SuppressWarnings("unchecked") private CompletableFuture<Void> bootstrap(Member member, CompletableFuture<Void> future) { LOGGER.debug("{} - Bootstrapping from member {}", membershipService.getLocalMember().id(), member); messagingService.<PartitionGroupInfo, PartitionGroupInfo>send( BOOTSTRAP_SUBJECT, new PartitionGroupInfo(membershipService.getLocalMember().id(), systemGroup, Lists.newArrayList(groups.values())), serializer::encode, serializer::decode, member.id()) .whenCompleteAsync((info, error) -> { if (error == null) { try { updatePartitionGroups(info); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); } } else { error = Throwables.getRootCause(error); if (error instanceof MessagingException.NoRemoteHandler || error instanceof TimeoutException) { threadContext.schedule(Duration.ofSeconds(1), () -> bootstrap(member, future)); } else { LOGGER.debug("{} - Failed to bootstrap from member {}", membershipService.getLocalMember().id(), member, error); future.complete(null); } } }, threadContext); return future; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "CompletableFuture", "<", "Void", ">", "bootstrap", "(", "Member", "member", ",", "CompletableFuture", "<", "Void", ">", "future", ")", "{", "LOGGER", ".", "debug", "(", "\"{} - Bootstrapping from member {}\"", ",", "membershipService", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ",", "member", ")", ";", "messagingService", ".", "<", "PartitionGroupInfo", ",", "PartitionGroupInfo", ">", "send", "(", "BOOTSTRAP_SUBJECT", ",", "new", "PartitionGroupInfo", "(", "membershipService", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ",", "systemGroup", ",", "Lists", ".", "newArrayList", "(", "groups", ".", "values", "(", ")", ")", ")", ",", "serializer", "::", "encode", ",", "serializer", "::", "decode", ",", "member", ".", "id", "(", ")", ")", ".", "whenCompleteAsync", "(", "(", "info", ",", "error", ")", "->", "{", "if", "(", "error", "==", "null", ")", "{", "try", "{", "updatePartitionGroups", "(", "info", ")", ";", "future", ".", "complete", "(", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "future", ".", "completeExceptionally", "(", "e", ")", ";", "}", "}", "else", "{", "error", "=", "Throwables", ".", "getRootCause", "(", "error", ")", ";", "if", "(", "error", "instanceof", "MessagingException", ".", "NoRemoteHandler", "||", "error", "instanceof", "TimeoutException", ")", "{", "threadContext", ".", "schedule", "(", "Duration", ".", "ofSeconds", "(", "1", ")", ",", "(", ")", "->", "bootstrap", "(", "member", ",", "future", ")", ")", ";", "}", "else", "{", "LOGGER", ".", "debug", "(", "\"{} - Failed to bootstrap from member {}\"", ",", "membershipService", ".", "getLocalMember", "(", ")", ".", "id", "(", ")", ",", "member", ",", "error", ")", ";", "future", ".", "complete", "(", "null", ")", ";", "}", "}", "}", ",", "threadContext", ")", ";", "return", "future", ";", "}" ]
Bootstraps the service from the given node.
[ "Bootstraps", "the", "service", "from", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/partition/impl/DefaultPartitionGroupMembershipService.java#L219-L247
27,446
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/PrimaryBackupPartition.java
PrimaryBackupPartition.join
CompletableFuture<Partition> join( PartitionManagementService managementService, ThreadContextFactory threadFactory) { election = managementService.getElectionService().getElectionFor(partitionId); server = new PrimaryBackupPartitionServer( this, managementService, memberGroupProvider, threadFactory); client = new PrimaryBackupPartitionClient(this, managementService, threadFactory); return server.start().thenCompose(v -> client.start()).thenApply(v -> this); }
java
CompletableFuture<Partition> join( PartitionManagementService managementService, ThreadContextFactory threadFactory) { election = managementService.getElectionService().getElectionFor(partitionId); server = new PrimaryBackupPartitionServer( this, managementService, memberGroupProvider, threadFactory); client = new PrimaryBackupPartitionClient(this, managementService, threadFactory); return server.start().thenCompose(v -> client.start()).thenApply(v -> this); }
[ "CompletableFuture", "<", "Partition", ">", "join", "(", "PartitionManagementService", "managementService", ",", "ThreadContextFactory", "threadFactory", ")", "{", "election", "=", "managementService", ".", "getElectionService", "(", ")", ".", "getElectionFor", "(", "partitionId", ")", ";", "server", "=", "new", "PrimaryBackupPartitionServer", "(", "this", ",", "managementService", ",", "memberGroupProvider", ",", "threadFactory", ")", ";", "client", "=", "new", "PrimaryBackupPartitionClient", "(", "this", ",", "managementService", ",", "threadFactory", ")", ";", "return", "server", ".", "start", "(", ")", ".", "thenCompose", "(", "v", "->", "client", ".", "start", "(", ")", ")", ".", "thenApply", "(", "v", "->", "this", ")", ";", "}" ]
Joins the primary-backup partition.
[ "Joins", "the", "primary", "-", "backup", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/PrimaryBackupPartition.java#L105-L116
27,447
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/PrimaryBackupPartition.java
PrimaryBackupPartition.connect
CompletableFuture<Partition> connect( PartitionManagementService managementService, ThreadContextFactory threadFactory) { election = managementService.getElectionService().getElectionFor(partitionId); client = new PrimaryBackupPartitionClient(this, managementService, threadFactory); return client.start().thenApply(v -> this); }
java
CompletableFuture<Partition> connect( PartitionManagementService managementService, ThreadContextFactory threadFactory) { election = managementService.getElectionService().getElectionFor(partitionId); client = new PrimaryBackupPartitionClient(this, managementService, threadFactory); return client.start().thenApply(v -> this); }
[ "CompletableFuture", "<", "Partition", ">", "connect", "(", "PartitionManagementService", "managementService", ",", "ThreadContextFactory", "threadFactory", ")", "{", "election", "=", "managementService", ".", "getElectionService", "(", ")", ".", "getElectionFor", "(", "partitionId", ")", ";", "client", "=", "new", "PrimaryBackupPartitionClient", "(", "this", ",", "managementService", ",", "threadFactory", ")", ";", "return", "client", ".", "start", "(", ")", ".", "thenApply", "(", "v", "->", "this", ")", ";", "}" ]
Connects to the primary-backup partition.
[ "Connects", "to", "the", "primary", "-", "backup", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/PrimaryBackupPartition.java#L121-L127
27,448
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/PrimaryBackupPartition.java
PrimaryBackupPartition.close
public CompletableFuture<Void> close() { if (client == null) { return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); client.stop().whenComplete((clientResult, clientError) -> { if (server != null) { server.stop().whenComplete((serverResult, serverError) -> { future.complete(null); }); } else { future.complete(null); } }); return future; }
java
public CompletableFuture<Void> close() { if (client == null) { return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); client.stop().whenComplete((clientResult, clientError) -> { if (server != null) { server.stop().whenComplete((serverResult, serverError) -> { future.complete(null); }); } else { future.complete(null); } }); return future; }
[ "public", "CompletableFuture", "<", "Void", ">", "close", "(", ")", "{", "if", "(", "client", "==", "null", ")", "{", "return", "CompletableFuture", ".", "completedFuture", "(", "null", ")", ";", "}", "CompletableFuture", "<", "Void", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "client", ".", "stop", "(", ")", ".", "whenComplete", "(", "(", "clientResult", ",", "clientError", ")", "->", "{", "if", "(", "server", "!=", "null", ")", "{", "server", ".", "stop", "(", ")", ".", "whenComplete", "(", "(", "serverResult", ",", "serverError", ")", "->", "{", "future", ".", "complete", "(", "null", ")", ";", "}", ")", ";", "}", "else", "{", "future", ".", "complete", "(", "null", ")", ";", "}", "}", ")", ";", "return", "future", ";", "}" ]
Closes the primary-backup partition.
[ "Closes", "the", "primary", "-", "backup", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/partition/PrimaryBackupPartition.java#L132-L148
27,449
atomix/atomix
core/src/main/java/io/atomix/core/utils/config/PolymorphicConfigMapper.java
PolymorphicConfigMapper.isPolymorphicType
private boolean isPolymorphicType(Class<?> clazz) { return polymorphicTypes.stream().anyMatch(polymorphicType -> polymorphicType.getConfigClass() == clazz); }
java
private boolean isPolymorphicType(Class<?> clazz) { return polymorphicTypes.stream().anyMatch(polymorphicType -> polymorphicType.getConfigClass() == clazz); }
[ "private", "boolean", "isPolymorphicType", "(", "Class", "<", "?", ">", "clazz", ")", "{", "return", "polymorphicTypes", ".", "stream", "(", ")", ".", "anyMatch", "(", "polymorphicType", "->", "polymorphicType", ".", "getConfigClass", "(", ")", "==", "clazz", ")", ";", "}" ]
Returns a boolean indicating whether the given class is a polymorphic type.
[ "Returns", "a", "boolean", "indicating", "whether", "the", "given", "class", "is", "a", "polymorphic", "type", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/utils/config/PolymorphicConfigMapper.java#L112-L114
27,450
atomix/atomix
primitive/src/main/java/io/atomix/primitive/event/Events.java
Events.findMethods
private static Map<Method, EventType> findMethods(Class<?> type) { Map<Method, EventType> events = new HashMap<>(); for (Method method : type.getDeclaredMethods()) { Event event = method.getAnnotation(Event.class); if (event != null) { String name = event.value().equals("") ? method.getName() : event.value(); events.put(method, EventType.from(name)); } } for (Class<?> iface : type.getInterfaces()) { events.putAll(findMethods(iface)); } return events; }
java
private static Map<Method, EventType> findMethods(Class<?> type) { Map<Method, EventType> events = new HashMap<>(); for (Method method : type.getDeclaredMethods()) { Event event = method.getAnnotation(Event.class); if (event != null) { String name = event.value().equals("") ? method.getName() : event.value(); events.put(method, EventType.from(name)); } } for (Class<?> iface : type.getInterfaces()) { events.putAll(findMethods(iface)); } return events; }
[ "private", "static", "Map", "<", "Method", ",", "EventType", ">", "findMethods", "(", "Class", "<", "?", ">", "type", ")", "{", "Map", "<", "Method", ",", "EventType", ">", "events", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Method", "method", ":", "type", ".", "getDeclaredMethods", "(", ")", ")", "{", "Event", "event", "=", "method", ".", "getAnnotation", "(", "Event", ".", "class", ")", ";", "if", "(", "event", "!=", "null", ")", "{", "String", "name", "=", "event", ".", "value", "(", ")", ".", "equals", "(", "\"\"", ")", "?", "method", ".", "getName", "(", ")", ":", "event", ".", "value", "(", ")", ";", "events", ".", "put", "(", "method", ",", "EventType", ".", "from", "(", "name", ")", ")", ";", "}", "}", "for", "(", "Class", "<", "?", ">", "iface", ":", "type", ".", "getInterfaces", "(", ")", ")", "{", "events", ".", "putAll", "(", "findMethods", "(", "iface", ")", ")", ";", "}", "return", "events", ";", "}" ]
Recursively finds events defined by the given type and its implemented interfaces. @param type the type for which to find events @return the events defined by the given type and its parent interfaces
[ "Recursively", "finds", "events", "defined", "by", "the", "given", "type", "and", "its", "implemented", "interfaces", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/event/Events.java#L50-L63
27,451
atomix/atomix
utils/src/main/java/io/atomix/utils/serializer/SerializerBuilder.java
SerializerBuilder.addSerializer
public SerializerBuilder addSerializer(com.esotericsoftware.kryo.Serializer serializer, Class<?>... types) { namespaceBuilder.register(serializer, types); return this; }
java
public SerializerBuilder addSerializer(com.esotericsoftware.kryo.Serializer serializer, Class<?>... types) { namespaceBuilder.register(serializer, types); return this; }
[ "public", "SerializerBuilder", "addSerializer", "(", "com", ".", "esotericsoftware", ".", "kryo", ".", "Serializer", "serializer", ",", "Class", "<", "?", ">", "...", "types", ")", "{", "namespaceBuilder", ".", "register", "(", "serializer", ",", "types", ")", ";", "return", "this", ";", "}" ]
Adds a serializer to the builder. @param serializer the serializer to add @param types the serializable types @return the serializer builder
[ "Adds", "a", "serializer", "to", "the", "builder", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/serializer/SerializerBuilder.java#L117-L120
27,452
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java
RaftSessionConnection.reset
public void reset(MemberId leader, Collection<MemberId> servers) { selector.reset(leader, servers); }
java
public void reset(MemberId leader, Collection<MemberId> servers) { selector.reset(leader, servers); }
[ "public", "void", "reset", "(", "MemberId", "leader", ",", "Collection", "<", "MemberId", ">", "servers", ")", "{", "selector", ".", "reset", "(", "leader", ",", "servers", ")", ";", "}" ]
Resets the member selector. @param leader the selector leader @param servers the selector servers
[ "Resets", "the", "member", "selector", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java#L93-L95
27,453
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java
RaftSessionConnection.openSession
public CompletableFuture<OpenSessionResponse> openSession(OpenSessionRequest request) { CompletableFuture<OpenSessionResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::openSession, future); } else { context.execute(() -> sendRequest(request, protocol::openSession, future)); } return future; }
java
public CompletableFuture<OpenSessionResponse> openSession(OpenSessionRequest request) { CompletableFuture<OpenSessionResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::openSession, future); } else { context.execute(() -> sendRequest(request, protocol::openSession, future)); } return future; }
[ "public", "CompletableFuture", "<", "OpenSessionResponse", ">", "openSession", "(", "OpenSessionRequest", "request", ")", "{", "CompletableFuture", "<", "OpenSessionResponse", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "if", "(", "context", ".", "isCurrentContext", "(", ")", ")", "{", "sendRequest", "(", "request", ",", "protocol", "::", "openSession", ",", "future", ")", ";", "}", "else", "{", "context", ".", "execute", "(", "(", ")", "->", "sendRequest", "(", "request", ",", "protocol", "::", "openSession", ",", "future", ")", ")", ";", "}", "return", "future", ";", "}" ]
Sends an open session request to the given node. @param request the request to send @return a future to be completed with the response
[ "Sends", "an", "open", "session", "request", "to", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java#L121-L129
27,454
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java
RaftSessionConnection.closeSession
public CompletableFuture<CloseSessionResponse> closeSession(CloseSessionRequest request) { CompletableFuture<CloseSessionResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::closeSession, future); } else { context.execute(() -> sendRequest(request, protocol::closeSession, future)); } return future; }
java
public CompletableFuture<CloseSessionResponse> closeSession(CloseSessionRequest request) { CompletableFuture<CloseSessionResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::closeSession, future); } else { context.execute(() -> sendRequest(request, protocol::closeSession, future)); } return future; }
[ "public", "CompletableFuture", "<", "CloseSessionResponse", ">", "closeSession", "(", "CloseSessionRequest", "request", ")", "{", "CompletableFuture", "<", "CloseSessionResponse", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "if", "(", "context", ".", "isCurrentContext", "(", ")", ")", "{", "sendRequest", "(", "request", ",", "protocol", "::", "closeSession", ",", "future", ")", ";", "}", "else", "{", "context", ".", "execute", "(", "(", ")", "->", "sendRequest", "(", "request", ",", "protocol", "::", "closeSession", ",", "future", ")", ")", ";", "}", "return", "future", ";", "}" ]
Sends a close session request to the given node. @param request the request to send @return a future to be completed with the response
[ "Sends", "a", "close", "session", "request", "to", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java#L137-L145
27,455
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java
RaftSessionConnection.keepAlive
public CompletableFuture<KeepAliveResponse> keepAlive(KeepAliveRequest request) { CompletableFuture<KeepAliveResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::keepAlive, future); } else { context.execute(() -> sendRequest(request, protocol::keepAlive, future)); } return future; }
java
public CompletableFuture<KeepAliveResponse> keepAlive(KeepAliveRequest request) { CompletableFuture<KeepAliveResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::keepAlive, future); } else { context.execute(() -> sendRequest(request, protocol::keepAlive, future)); } return future; }
[ "public", "CompletableFuture", "<", "KeepAliveResponse", ">", "keepAlive", "(", "KeepAliveRequest", "request", ")", "{", "CompletableFuture", "<", "KeepAliveResponse", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "if", "(", "context", ".", "isCurrentContext", "(", ")", ")", "{", "sendRequest", "(", "request", ",", "protocol", "::", "keepAlive", ",", "future", ")", ";", "}", "else", "{", "context", ".", "execute", "(", "(", ")", "->", "sendRequest", "(", "request", ",", "protocol", "::", "keepAlive", ",", "future", ")", ")", ";", "}", "return", "future", ";", "}" ]
Sends a keep alive request to the given node. @param request the request to send @return a future to be completed with the response
[ "Sends", "a", "keep", "alive", "request", "to", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java#L153-L161
27,456
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java
RaftSessionConnection.query
public CompletableFuture<QueryResponse> query(QueryRequest request) { CompletableFuture<QueryResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::query, future); } else { context.execute(() -> sendRequest(request, protocol::query, future)); } return future; }
java
public CompletableFuture<QueryResponse> query(QueryRequest request) { CompletableFuture<QueryResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::query, future); } else { context.execute(() -> sendRequest(request, protocol::query, future)); } return future; }
[ "public", "CompletableFuture", "<", "QueryResponse", ">", "query", "(", "QueryRequest", "request", ")", "{", "CompletableFuture", "<", "QueryResponse", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "if", "(", "context", ".", "isCurrentContext", "(", ")", ")", "{", "sendRequest", "(", "request", ",", "protocol", "::", "query", ",", "future", ")", ";", "}", "else", "{", "context", ".", "execute", "(", "(", ")", "->", "sendRequest", "(", "request", ",", "protocol", "::", "query", ",", "future", ")", ")", ";", "}", "return", "future", ";", "}" ]
Sends a query request to the given node. @param request the request to send @return a future to be completed with the response
[ "Sends", "a", "query", "request", "to", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java#L169-L177
27,457
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java
RaftSessionConnection.command
public CompletableFuture<CommandResponse> command(CommandRequest request) { CompletableFuture<CommandResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::command, future); } else { context.execute(() -> sendRequest(request, protocol::command, future)); } return future; }
java
public CompletableFuture<CommandResponse> command(CommandRequest request) { CompletableFuture<CommandResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::command, future); } else { context.execute(() -> sendRequest(request, protocol::command, future)); } return future; }
[ "public", "CompletableFuture", "<", "CommandResponse", ">", "command", "(", "CommandRequest", "request", ")", "{", "CompletableFuture", "<", "CommandResponse", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "if", "(", "context", ".", "isCurrentContext", "(", ")", ")", "{", "sendRequest", "(", "request", ",", "protocol", "::", "command", ",", "future", ")", ";", "}", "else", "{", "context", ".", "execute", "(", "(", ")", "->", "sendRequest", "(", "request", ",", "protocol", "::", "command", ",", "future", ")", ")", ";", "}", "return", "future", ";", "}" ]
Sends a command request to the given node. @param request the request to send @return a future to be completed with the response
[ "Sends", "a", "command", "request", "to", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java#L185-L193
27,458
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java
RaftSessionConnection.metadata
public CompletableFuture<MetadataResponse> metadata(MetadataRequest request) { CompletableFuture<MetadataResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::metadata, future); } else { context.execute(() -> sendRequest(request, protocol::metadata, future)); } return future; }
java
public CompletableFuture<MetadataResponse> metadata(MetadataRequest request) { CompletableFuture<MetadataResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::metadata, future); } else { context.execute(() -> sendRequest(request, protocol::metadata, future)); } return future; }
[ "public", "CompletableFuture", "<", "MetadataResponse", ">", "metadata", "(", "MetadataRequest", "request", ")", "{", "CompletableFuture", "<", "MetadataResponse", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "if", "(", "context", ".", "isCurrentContext", "(", ")", ")", "{", "sendRequest", "(", "request", ",", "protocol", "::", "metadata", ",", "future", ")", ";", "}", "else", "{", "context", ".", "execute", "(", "(", ")", "->", "sendRequest", "(", "request", ",", "protocol", "::", "metadata", ",", "future", ")", ")", ";", "}", "return", "future", ";", "}" ]
Sends a metadata request to the given node. @param request the request to send @return a future to be completed with the response
[ "Sends", "a", "metadata", "request", "to", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionConnection.java#L201-L209
27,459
atomix/atomix
storage/src/main/java/io/atomix/storage/buffer/MappedBytes.java
MappedBytes.delete
public void delete() { try { close(); Files.delete(file.toPath()); } catch (IOException e) { throw new RuntimeException(e); } }
java
public void delete() { try { close(); Files.delete(file.toPath()); } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "void", "delete", "(", ")", "{", "try", "{", "close", "(", ")", ";", "Files", ".", "delete", "(", "file", ".", "toPath", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Deletes the underlying file.
[ "Deletes", "the", "underlying", "file", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/storage/src/main/java/io/atomix/storage/buffer/MappedBytes.java#L124-L131
27,460
atomix/atomix
core/src/main/java/io/atomix/core/iterator/impl/ProxyIterator.java
ProxyIterator.batch
private CompletableFuture<Iterator<T>> batch() { return batch.thenCompose(iterator -> { if (iterator != null && !iterator.hasNext()) { batch = fetch(iterator.position()); return batch.thenApply(Function.identity()); } return CompletableFuture.completedFuture(iterator); }); }
java
private CompletableFuture<Iterator<T>> batch() { return batch.thenCompose(iterator -> { if (iterator != null && !iterator.hasNext()) { batch = fetch(iterator.position()); return batch.thenApply(Function.identity()); } return CompletableFuture.completedFuture(iterator); }); }
[ "private", "CompletableFuture", "<", "Iterator", "<", "T", ">", ">", "batch", "(", ")", "{", "return", "batch", ".", "thenCompose", "(", "iterator", "->", "{", "if", "(", "iterator", "!=", "null", "&&", "!", "iterator", ".", "hasNext", "(", ")", ")", "{", "batch", "=", "fetch", "(", "iterator", ".", "position", "(", ")", ")", ";", "return", "batch", ".", "thenApply", "(", "Function", ".", "identity", "(", ")", ")", ";", "}", "return", "CompletableFuture", ".", "completedFuture", "(", "iterator", ")", ";", "}", ")", ";", "}" ]
Returns the current batch iterator or lazily fetches the next batch from the cluster. @return the next batch iterator
[ "Returns", "the", "current", "batch", "iterator", "or", "lazily", "fetches", "the", "next", "batch", "from", "the", "cluster", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/iterator/impl/ProxyIterator.java#L60-L68
27,461
atomix/atomix
core/src/main/java/io/atomix/core/iterator/impl/ProxyIterator.java
ProxyIterator.fetch
private CompletableFuture<IteratorBatch<T>> fetch(int position) { return openFuture.thenCompose(initialBatch -> { if (!initialBatch.complete()) { return client.applyOn(partitionId, service -> nextFunction.next(service, initialBatch.id(), position)) .thenCompose(nextBatch -> { if (nextBatch == null) { return close().thenApply(v -> null); } return CompletableFuture.completedFuture(nextBatch); }); } return CompletableFuture.completedFuture(null); }); }
java
private CompletableFuture<IteratorBatch<T>> fetch(int position) { return openFuture.thenCompose(initialBatch -> { if (!initialBatch.complete()) { return client.applyOn(partitionId, service -> nextFunction.next(service, initialBatch.id(), position)) .thenCompose(nextBatch -> { if (nextBatch == null) { return close().thenApply(v -> null); } return CompletableFuture.completedFuture(nextBatch); }); } return CompletableFuture.completedFuture(null); }); }
[ "private", "CompletableFuture", "<", "IteratorBatch", "<", "T", ">", ">", "fetch", "(", "int", "position", ")", "{", "return", "openFuture", ".", "thenCompose", "(", "initialBatch", "->", "{", "if", "(", "!", "initialBatch", ".", "complete", "(", ")", ")", "{", "return", "client", ".", "applyOn", "(", "partitionId", ",", "service", "->", "nextFunction", ".", "next", "(", "service", ",", "initialBatch", ".", "id", "(", ")", ",", "position", ")", ")", ".", "thenCompose", "(", "nextBatch", "->", "{", "if", "(", "nextBatch", "==", "null", ")", "{", "return", "close", "(", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}", "return", "CompletableFuture", ".", "completedFuture", "(", "nextBatch", ")", ";", "}", ")", ";", "}", "return", "CompletableFuture", ".", "completedFuture", "(", "null", ")", ";", "}", ")", ";", "}" ]
Fetches the next batch of entries from the cluster. @param position the position from which to fetch the next batch @return the next batch of entries from the cluster
[ "Fetches", "the", "next", "batch", "of", "entries", "from", "the", "cluster", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/iterator/impl/ProxyIterator.java#L76-L89
27,462
atomix/atomix
cluster/src/main/java/io/atomix/cluster/MulticastConfig.java
MulticastConfig.setGroup
public MulticastConfig setGroup(String group) { try { InetAddress address = InetAddress.getByName(group); if (!address.isMulticastAddress()) { throw new ConfigurationException("Invalid multicast group " + group); } return setGroup(address); } catch (UnknownHostException e) { throw new ConfigurationException("Failed to locate multicast group", e); } }
java
public MulticastConfig setGroup(String group) { try { InetAddress address = InetAddress.getByName(group); if (!address.isMulticastAddress()) { throw new ConfigurationException("Invalid multicast group " + group); } return setGroup(address); } catch (UnknownHostException e) { throw new ConfigurationException("Failed to locate multicast group", e); } }
[ "public", "MulticastConfig", "setGroup", "(", "String", "group", ")", "{", "try", "{", "InetAddress", "address", "=", "InetAddress", ".", "getByName", "(", "group", ")", ";", "if", "(", "!", "address", ".", "isMulticastAddress", "(", ")", ")", "{", "throw", "new", "ConfigurationException", "(", "\"Invalid multicast group \"", "+", "group", ")", ";", "}", "return", "setGroup", "(", "address", ")", ";", "}", "catch", "(", "UnknownHostException", "e", ")", "{", "throw", "new", "ConfigurationException", "(", "\"Failed to locate multicast group\"", ",", "e", ")", ";", "}", "}" ]
Sets the multicast group. @param group the multicast group @return the multicast configuration @throws ConfigurationException if the group is invalid
[ "Sets", "the", "multicast", "group", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/MulticastConfig.java#L81-L91
27,463
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/AbstractAccumulator.java
AbstractAccumulator.rescheduleTask
private void rescheduleTask(AtomicReference<TimerTask> taskRef, long millis) { ProcessorTask newTask = new ProcessorTask(); timer.schedule(newTask, millis); swapAndCancelTask(taskRef, newTask); }
java
private void rescheduleTask(AtomicReference<TimerTask> taskRef, long millis) { ProcessorTask newTask = new ProcessorTask(); timer.schedule(newTask, millis); swapAndCancelTask(taskRef, newTask); }
[ "private", "void", "rescheduleTask", "(", "AtomicReference", "<", "TimerTask", ">", "taskRef", ",", "long", "millis", ")", "{", "ProcessorTask", "newTask", "=", "new", "ProcessorTask", "(", ")", ";", "timer", ".", "schedule", "(", "newTask", ",", "millis", ")", ";", "swapAndCancelTask", "(", "taskRef", ",", "newTask", ")", ";", "}" ]
Reschedules the specified task, cancelling existing one if applicable. @param taskRef task reference @param millis delay in milliseconds
[ "Reschedules", "the", "specified", "task", "cancelling", "existing", "one", "if", "applicable", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/AbstractAccumulator.java#L124-L128
27,464
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/AbstractAccumulator.java
AbstractAccumulator.swapAndCancelTask
private void swapAndCancelTask(AtomicReference<TimerTask> taskRef, TimerTask newTask) { TimerTask oldTask = taskRef.getAndSet(newTask); if (oldTask != null) { oldTask.cancel(); } }
java
private void swapAndCancelTask(AtomicReference<TimerTask> taskRef, TimerTask newTask) { TimerTask oldTask = taskRef.getAndSet(newTask); if (oldTask != null) { oldTask.cancel(); } }
[ "private", "void", "swapAndCancelTask", "(", "AtomicReference", "<", "TimerTask", ">", "taskRef", ",", "TimerTask", "newTask", ")", "{", "TimerTask", "oldTask", "=", "taskRef", ".", "getAndSet", "(", "newTask", ")", ";", "if", "(", "oldTask", "!=", "null", ")", "{", "oldTask", ".", "cancel", "(", ")", ";", "}", "}" ]
Sets the new task and attempts to cancelTask the old one. @param taskRef task reference @param newTask new task
[ "Sets", "the", "new", "task", "and", "attempts", "to", "cancelTask", "the", "old", "one", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/AbstractAccumulator.java#L145-L151
27,465
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/AbstractAccumulator.java
AbstractAccumulator.finalizeCurrentBatch
private List<T> finalizeCurrentBatch() { List<T> finalizedList; synchronized (items) { finalizedList = ImmutableList.copyOf(items); items.clear(); /* * To avoid reprocessing being triggered on an empty list. */ cancelTask(maxTask); cancelTask(idleTask); } return finalizedList; }
java
private List<T> finalizeCurrentBatch() { List<T> finalizedList; synchronized (items) { finalizedList = ImmutableList.copyOf(items); items.clear(); /* * To avoid reprocessing being triggered on an empty list. */ cancelTask(maxTask); cancelTask(idleTask); } return finalizedList; }
[ "private", "List", "<", "T", ">", "finalizeCurrentBatch", "(", ")", "{", "List", "<", "T", ">", "finalizedList", ";", "synchronized", "(", "items", ")", "{", "finalizedList", "=", "ImmutableList", ".", "copyOf", "(", "items", ")", ";", "items", ".", "clear", "(", ")", ";", "/*\n * To avoid reprocessing being triggered on an empty list.\n */", "cancelTask", "(", "maxTask", ")", ";", "cancelTask", "(", "idleTask", ")", ";", "}", "return", "finalizedList", ";", "}" ]
Returns an immutable copy of the existing items and clear the list. @return list of existing items
[ "Returns", "an", "immutable", "copy", "of", "the", "existing", "items", "and", "clear", "the", "list", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/AbstractAccumulator.java#L178-L190
27,466
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java
CrdtSetDelegate.set
protected Set<E> set() { return elements.entrySet() .stream() .filter(entry -> !entry.getValue().isTombstone()) .map(entry -> decode(entry.getKey())) .collect(Collectors.toSet()); }
java
protected Set<E> set() { return elements.entrySet() .stream() .filter(entry -> !entry.getValue().isTombstone()) .map(entry -> decode(entry.getKey())) .collect(Collectors.toSet()); }
[ "protected", "Set", "<", "E", ">", "set", "(", ")", "{", "return", "elements", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "entry", "->", "!", "entry", ".", "getValue", "(", ")", ".", "isTombstone", "(", ")", ")", ".", "map", "(", "entry", "->", "decode", "(", "entry", ".", "getKey", "(", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "}" ]
Returns the computed set. @return the computed set
[ "Returns", "the", "computed", "set", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java#L193-L199
27,467
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java
CrdtSetDelegate.encode
private String encode(Object element) { return BaseEncoding.base16().encode(elementSerializer.encode(element)); }
java
private String encode(Object element) { return BaseEncoding.base16().encode(elementSerializer.encode(element)); }
[ "private", "String", "encode", "(", "Object", "element", ")", "{", "return", "BaseEncoding", ".", "base16", "(", ")", ".", "encode", "(", "elementSerializer", ".", "encode", "(", "element", ")", ")", ";", "}" ]
Encodes the given element to a string for internal storage. @param element the element to encode @return the encoded element
[ "Encodes", "the", "given", "element", "to", "a", "string", "for", "internal", "storage", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java#L207-L209
27,468
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java
CrdtSetDelegate.decode
protected E decode(String element) { return elementSerializer.decode(BaseEncoding.base16().decode(element)); }
java
protected E decode(String element) { return elementSerializer.decode(BaseEncoding.base16().decode(element)); }
[ "protected", "E", "decode", "(", "String", "element", ")", "{", "return", "elementSerializer", ".", "decode", "(", "BaseEncoding", ".", "base16", "(", ")", ".", "decode", "(", "element", ")", ")", ";", "}" ]
Decodes the given element from a string. @param element the element to decode @return the decoded element
[ "Decodes", "the", "given", "element", "from", "a", "string", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java#L217-L219
27,469
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java
CrdtSetDelegate.updateElements
private void updateElements(Map<String, SetElement> elements) { for (SetElement element : elements.values()) { if (element.isTombstone()) { if (remove(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.REMOVE, decode(element.value())))); } } else { if (add(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.ADD, decode(element.value())))); } } } }
java
private void updateElements(Map<String, SetElement> elements) { for (SetElement element : elements.values()) { if (element.isTombstone()) { if (remove(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.REMOVE, decode(element.value())))); } } else { if (add(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.ADD, decode(element.value())))); } } } }
[ "private", "void", "updateElements", "(", "Map", "<", "String", ",", "SetElement", ">", "elements", ")", "{", "for", "(", "SetElement", "element", ":", "elements", ".", "values", "(", ")", ")", "{", "if", "(", "element", ".", "isTombstone", "(", ")", ")", "{", "if", "(", "remove", "(", "element", ")", ")", "{", "eventListeners", ".", "forEach", "(", "listener", "->", "listener", ".", "event", "(", "new", "SetDelegateEvent", "<>", "(", "SetDelegateEvent", ".", "Type", ".", "REMOVE", ",", "decode", "(", "element", ".", "value", "(", ")", ")", ")", ")", ")", ";", "}", "}", "else", "{", "if", "(", "add", "(", "element", ")", ")", "{", "eventListeners", ".", "forEach", "(", "listener", "->", "listener", ".", "event", "(", "new", "SetDelegateEvent", "<>", "(", "SetDelegateEvent", ".", "Type", ".", "ADD", ",", "decode", "(", "element", ".", "value", "(", ")", ")", ")", ")", ")", ";", "}", "}", "}", "}" ]
Updates the set elements. @param elements the elements to update
[ "Updates", "the", "set", "elements", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java#L226-L238
27,470
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/PrimaryBackupClient.java
PrimaryBackupClient.sessionBuilder
public PrimaryBackupSessionClient.Builder sessionBuilder(String primitiveName, PrimitiveType primitiveType, ServiceConfig serviceConfig) { byte[] configBytes = Serializer.using(primitiveType.namespace()).encode(serviceConfig); return new PrimaryBackupSessionClient.Builder() { @Override public SessionClient build() { Supplier<CompletableFuture<SessionClient>> proxyBuilder = () -> sessionIdService.nextSessionId() .thenApply(sessionId -> new PrimaryBackupSessionClient( clientName, partitionId, sessionId, primitiveType, new PrimitiveDescriptor( primitiveName, primitiveType.name(), configBytes, numBackups, replication), clusterMembershipService, PrimaryBackupClient.this.protocol, primaryElection, threadContextFactory.createContext())); SessionClient proxy; ThreadContext context = threadContextFactory.createContext(); if (recovery == Recovery.RECOVER) { proxy = new RecoveringSessionClient( clientName, partitionId, primitiveName, primitiveType, proxyBuilder, context); } else { proxy = Futures.get(proxyBuilder.get()); } // If max retries is set, wrap the client in a retrying proxy client. if (maxRetries > 0) { proxy = new RetryingSessionClient( proxy, context, maxRetries, retryDelay); } return new BlockingAwareSessionClient(proxy, context); } }; }
java
public PrimaryBackupSessionClient.Builder sessionBuilder(String primitiveName, PrimitiveType primitiveType, ServiceConfig serviceConfig) { byte[] configBytes = Serializer.using(primitiveType.namespace()).encode(serviceConfig); return new PrimaryBackupSessionClient.Builder() { @Override public SessionClient build() { Supplier<CompletableFuture<SessionClient>> proxyBuilder = () -> sessionIdService.nextSessionId() .thenApply(sessionId -> new PrimaryBackupSessionClient( clientName, partitionId, sessionId, primitiveType, new PrimitiveDescriptor( primitiveName, primitiveType.name(), configBytes, numBackups, replication), clusterMembershipService, PrimaryBackupClient.this.protocol, primaryElection, threadContextFactory.createContext())); SessionClient proxy; ThreadContext context = threadContextFactory.createContext(); if (recovery == Recovery.RECOVER) { proxy = new RecoveringSessionClient( clientName, partitionId, primitiveName, primitiveType, proxyBuilder, context); } else { proxy = Futures.get(proxyBuilder.get()); } // If max retries is set, wrap the client in a retrying proxy client. if (maxRetries > 0) { proxy = new RetryingSessionClient( proxy, context, maxRetries, retryDelay); } return new BlockingAwareSessionClient(proxy, context); } }; }
[ "public", "PrimaryBackupSessionClient", ".", "Builder", "sessionBuilder", "(", "String", "primitiveName", ",", "PrimitiveType", "primitiveType", ",", "ServiceConfig", "serviceConfig", ")", "{", "byte", "[", "]", "configBytes", "=", "Serializer", ".", "using", "(", "primitiveType", ".", "namespace", "(", ")", ")", ".", "encode", "(", "serviceConfig", ")", ";", "return", "new", "PrimaryBackupSessionClient", ".", "Builder", "(", ")", "{", "@", "Override", "public", "SessionClient", "build", "(", ")", "{", "Supplier", "<", "CompletableFuture", "<", "SessionClient", ">>", "proxyBuilder", "=", "(", ")", "->", "sessionIdService", ".", "nextSessionId", "(", ")", ".", "thenApply", "(", "sessionId", "->", "new", "PrimaryBackupSessionClient", "(", "clientName", ",", "partitionId", ",", "sessionId", ",", "primitiveType", ",", "new", "PrimitiveDescriptor", "(", "primitiveName", ",", "primitiveType", ".", "name", "(", ")", ",", "configBytes", ",", "numBackups", ",", "replication", ")", ",", "clusterMembershipService", ",", "PrimaryBackupClient", ".", "this", ".", "protocol", ",", "primaryElection", ",", "threadContextFactory", ".", "createContext", "(", ")", ")", ")", ";", "SessionClient", "proxy", ";", "ThreadContext", "context", "=", "threadContextFactory", ".", "createContext", "(", ")", ";", "if", "(", "recovery", "==", "Recovery", ".", "RECOVER", ")", "{", "proxy", "=", "new", "RecoveringSessionClient", "(", "clientName", ",", "partitionId", ",", "primitiveName", ",", "primitiveType", ",", "proxyBuilder", ",", "context", ")", ";", "}", "else", "{", "proxy", "=", "Futures", ".", "get", "(", "proxyBuilder", ".", "get", "(", ")", ")", ";", "}", "// If max retries is set, wrap the client in a retrying proxy client.", "if", "(", "maxRetries", ">", "0", ")", "{", "proxy", "=", "new", "RetryingSessionClient", "(", "proxy", ",", "context", ",", "maxRetries", ",", "retryDelay", ")", ";", "}", "return", "new", "BlockingAwareSessionClient", "(", "proxy", ",", "context", ")", ";", "}", "}", ";", "}" ]
Creates a new primary backup proxy session builder. @param primitiveName the primitive name @param primitiveType the primitive type @param serviceConfig the service configuration @return a new primary-backup proxy session builder
[ "Creates", "a", "new", "primary", "backup", "proxy", "session", "builder", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/PrimaryBackupClient.java#L99-L146
27,471
atomix/atomix
protocols/primary-backup/src/main/java/io/atomix/protocols/backup/PrimaryBackupClient.java
PrimaryBackupClient.close
public CompletableFuture<Void> close() { threadContext.close(); if (closeOnStop) { threadContextFactory.close(); } return CompletableFuture.completedFuture(null); }
java
public CompletableFuture<Void> close() { threadContext.close(); if (closeOnStop) { threadContextFactory.close(); } return CompletableFuture.completedFuture(null); }
[ "public", "CompletableFuture", "<", "Void", ">", "close", "(", ")", "{", "threadContext", ".", "close", "(", ")", ";", "if", "(", "closeOnStop", ")", "{", "threadContextFactory", ".", "close", "(", ")", ";", "}", "return", "CompletableFuture", ".", "completedFuture", "(", "null", ")", ";", "}" ]
Closes the primary-backup client. @return future to be completed once the client is closed
[ "Closes", "the", "primary", "-", "backup", "client", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/primary-backup/src/main/java/io/atomix/protocols/backup/PrimaryBackupClient.java#L153-L159
27,472
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/cluster/impl/RaftClusterContext.java
RaftClusterContext.resetJoinTimer
private void resetJoinTimer() { cancelJoinTimer(); joinTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout().multipliedBy(2), () -> { join(getActiveMemberStates().iterator()); }); }
java
private void resetJoinTimer() { cancelJoinTimer(); joinTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout().multipliedBy(2), () -> { join(getActiveMemberStates().iterator()); }); }
[ "private", "void", "resetJoinTimer", "(", ")", "{", "cancelJoinTimer", "(", ")", ";", "joinTimeout", "=", "raft", ".", "getThreadContext", "(", ")", ".", "schedule", "(", "raft", ".", "getElectionTimeout", "(", ")", ".", "multipliedBy", "(", "2", ")", ",", "(", ")", "->", "{", "join", "(", "getActiveMemberStates", "(", ")", ".", "iterator", "(", ")", ")", ";", "}", ")", ";", "}" ]
Resets the join timer.
[ "Resets", "the", "join", "timer", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/cluster/impl/RaftClusterContext.java#L448-L453
27,473
atomix/atomix
core/src/main/java/io/atomix/core/log/impl/DefaultAsyncDistributedLogPartition.java
DefaultAsyncDistributedLogPartition.produce
CompletableFuture<Void> produce(byte[] bytes) { return session.producer().append(bytes).thenApply(v -> null); }
java
CompletableFuture<Void> produce(byte[] bytes) { return session.producer().append(bytes).thenApply(v -> null); }
[ "CompletableFuture", "<", "Void", ">", "produce", "(", "byte", "[", "]", "bytes", ")", "{", "return", "session", ".", "producer", "(", ")", ".", "append", "(", "bytes", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}" ]
Produces the given bytes to the partition. @param bytes the bytes to produce @return a future to be completed once the bytes have been written to the partition
[ "Produces", "the", "given", "bytes", "to", "the", "partition", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/log/impl/DefaultAsyncDistributedLogPartition.java#L94-L96
27,474
atomix/atomix
primitive/src/main/java/io/atomix/primitive/service/AbstractPrimitiveService.java
AbstractPrimitiveService.configure
private void configure(OperationId operationId, Method method, ServiceExecutor executor) { if (method.getReturnType() == Void.TYPE) { if (method.getParameterTypes().length == 0) { executor.register(operationId, () -> { try { method.invoke(this); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } else { executor.register(operationId, args -> { try { method.invoke(this, (Object[]) args.value()); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } } else { if (method.getParameterTypes().length == 0) { executor.register(operationId, () -> { try { return method.invoke(this); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } else { executor.register(operationId, args -> { try { return method.invoke(this, (Object[]) args.value()); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } } }
java
private void configure(OperationId operationId, Method method, ServiceExecutor executor) { if (method.getReturnType() == Void.TYPE) { if (method.getParameterTypes().length == 0) { executor.register(operationId, () -> { try { method.invoke(this); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } else { executor.register(operationId, args -> { try { method.invoke(this, (Object[]) args.value()); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } } else { if (method.getParameterTypes().length == 0) { executor.register(operationId, () -> { try { return method.invoke(this); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } else { executor.register(operationId, args -> { try { return method.invoke(this, (Object[]) args.value()); } catch (IllegalAccessException | InvocationTargetException e) { throw new PrimitiveException.ServiceException(e); } }); } } }
[ "private", "void", "configure", "(", "OperationId", "operationId", ",", "Method", "method", ",", "ServiceExecutor", "executor", ")", "{", "if", "(", "method", ".", "getReturnType", "(", ")", "==", "Void", ".", "TYPE", ")", "{", "if", "(", "method", ".", "getParameterTypes", "(", ")", ".", "length", "==", "0", ")", "{", "executor", ".", "register", "(", "operationId", ",", "(", ")", "->", "{", "try", "{", "method", ".", "invoke", "(", "this", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "PrimitiveException", ".", "ServiceException", "(", "e", ")", ";", "}", "}", ")", ";", "}", "else", "{", "executor", ".", "register", "(", "operationId", ",", "args", "->", "{", "try", "{", "method", ".", "invoke", "(", "this", ",", "(", "Object", "[", "]", ")", "args", ".", "value", "(", ")", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "PrimitiveException", ".", "ServiceException", "(", "e", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "if", "(", "method", ".", "getParameterTypes", "(", ")", ".", "length", "==", "0", ")", "{", "executor", ".", "register", "(", "operationId", ",", "(", ")", "->", "{", "try", "{", "return", "method", ".", "invoke", "(", "this", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "PrimitiveException", ".", "ServiceException", "(", "e", ")", ";", "}", "}", ")", ";", "}", "else", "{", "executor", ".", "register", "(", "operationId", ",", "args", "->", "{", "try", "{", "return", "method", ".", "invoke", "(", "this", ",", "(", "Object", "[", "]", ")", "args", ".", "value", "(", ")", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "PrimitiveException", ".", "ServiceException", "(", "e", ")", ";", "}", "}", ")", ";", "}", "}", "}" ]
Configures the given operation on the given executor. @param operationId the operation identifier @param method the operation method @param executor the service executor
[ "Configures", "the", "given", "operation", "on", "the", "given", "executor", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/service/AbstractPrimitiveService.java#L136-L174
27,475
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/RaftStorage.java
RaftStorage.lock
public boolean lock(String id) { File file = new File(directory, String.format(".%s.lock", prefix)); try { if (file.createNewFile()) { try (FileBuffer buffer = FileBuffer.allocate(file)) { buffer.writeString(id).flush(); } return true; } else { try (FileBuffer buffer = FileBuffer.allocate(file)) { String lock = buffer.readString(); return lock != null && lock.equals(id); } } } catch (IOException e) { throw new StorageException("Failed to acquire storage lock"); } }
java
public boolean lock(String id) { File file = new File(directory, String.format(".%s.lock", prefix)); try { if (file.createNewFile()) { try (FileBuffer buffer = FileBuffer.allocate(file)) { buffer.writeString(id).flush(); } return true; } else { try (FileBuffer buffer = FileBuffer.allocate(file)) { String lock = buffer.readString(); return lock != null && lock.equals(id); } } } catch (IOException e) { throw new StorageException("Failed to acquire storage lock"); } }
[ "public", "boolean", "lock", "(", "String", "id", ")", "{", "File", "file", "=", "new", "File", "(", "directory", ",", "String", ".", "format", "(", "\".%s.lock\"", ",", "prefix", ")", ")", ";", "try", "{", "if", "(", "file", ".", "createNewFile", "(", ")", ")", "{", "try", "(", "FileBuffer", "buffer", "=", "FileBuffer", ".", "allocate", "(", "file", ")", ")", "{", "buffer", ".", "writeString", "(", "id", ")", ".", "flush", "(", ")", ";", "}", "return", "true", ";", "}", "else", "{", "try", "(", "FileBuffer", "buffer", "=", "FileBuffer", ".", "allocate", "(", "file", ")", ")", "{", "String", "lock", "=", "buffer", ".", "readString", "(", ")", ";", "return", "lock", "!=", "null", "&&", "lock", ".", "equals", "(", "id", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "StorageException", "(", "\"Failed to acquire storage lock\"", ")", ";", "}", "}" ]
Attempts to acquire a lock on the storage directory. @param id the ID with which to lock the directory @return indicates whether the lock was successfully acquired
[ "Attempts", "to", "acquire", "a", "lock", "on", "the", "storage", "directory", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/RaftStorage.java#L244-L261
27,476
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/RaftStorage.java
RaftStorage.deleteFiles
private void deleteFiles(Predicate<File> predicate) { directory.mkdirs(); // Iterate through all files in the storage directory. for (File file : directory.listFiles(f -> f.isFile() && predicate.test(f))) { try { Files.delete(file.toPath()); } catch (IOException e) { // Ignore the exception. } } }
java
private void deleteFiles(Predicate<File> predicate) { directory.mkdirs(); // Iterate through all files in the storage directory. for (File file : directory.listFiles(f -> f.isFile() && predicate.test(f))) { try { Files.delete(file.toPath()); } catch (IOException e) { // Ignore the exception. } } }
[ "private", "void", "deleteFiles", "(", "Predicate", "<", "File", ">", "predicate", ")", "{", "directory", ".", "mkdirs", "(", ")", ";", "// Iterate through all files in the storage directory.", "for", "(", "File", "file", ":", "directory", ".", "listFiles", "(", "f", "->", "f", ".", "isFile", "(", ")", "&&", "predicate", ".", "test", "(", "f", ")", ")", ")", "{", "try", "{", "Files", ".", "delete", "(", "file", ".", "toPath", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// Ignore the exception.", "}", "}", "}" ]
Deletes file in the storage directory that match the given predicate.
[ "Deletes", "file", "in", "the", "storage", "directory", "that", "match", "the", "given", "predicate", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/RaftStorage.java#L352-L363
27,477
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java
LeaderRole.drainCommands
private void drainCommands(long sequenceNumber, RaftSession session) { // First we need to drain any commands that exist in the queue *prior* to the next sequence number. This is // possible if commands from the prior term are committed after a leader change. long nextSequence = session.nextRequestSequence(); for (long i = sequenceNumber; i < nextSequence; i++) { PendingCommand nextCommand = session.removeCommand(i); if (nextCommand != null) { commitCommand(nextCommand.request(), nextCommand.future()); } } // Finally, drain any commands that are sequenced in the session. PendingCommand nextCommand = session.removeCommand(nextSequence); while (nextCommand != null) { commitCommand(nextCommand.request(), nextCommand.future()); session.setRequestSequence(nextSequence); nextSequence = session.nextRequestSequence(); nextCommand = session.removeCommand(nextSequence); } }
java
private void drainCommands(long sequenceNumber, RaftSession session) { // First we need to drain any commands that exist in the queue *prior* to the next sequence number. This is // possible if commands from the prior term are committed after a leader change. long nextSequence = session.nextRequestSequence(); for (long i = sequenceNumber; i < nextSequence; i++) { PendingCommand nextCommand = session.removeCommand(i); if (nextCommand != null) { commitCommand(nextCommand.request(), nextCommand.future()); } } // Finally, drain any commands that are sequenced in the session. PendingCommand nextCommand = session.removeCommand(nextSequence); while (nextCommand != null) { commitCommand(nextCommand.request(), nextCommand.future()); session.setRequestSequence(nextSequence); nextSequence = session.nextRequestSequence(); nextCommand = session.removeCommand(nextSequence); } }
[ "private", "void", "drainCommands", "(", "long", "sequenceNumber", ",", "RaftSession", "session", ")", "{", "// First we need to drain any commands that exist in the queue *prior* to the next sequence number. This is", "// possible if commands from the prior term are committed after a leader change.", "long", "nextSequence", "=", "session", ".", "nextRequestSequence", "(", ")", ";", "for", "(", "long", "i", "=", "sequenceNumber", ";", "i", "<", "nextSequence", ";", "i", "++", ")", "{", "PendingCommand", "nextCommand", "=", "session", ".", "removeCommand", "(", "i", ")", ";", "if", "(", "nextCommand", "!=", "null", ")", "{", "commitCommand", "(", "nextCommand", ".", "request", "(", ")", ",", "nextCommand", ".", "future", "(", ")", ")", ";", "}", "}", "// Finally, drain any commands that are sequenced in the session.", "PendingCommand", "nextCommand", "=", "session", ".", "removeCommand", "(", "nextSequence", ")", ";", "while", "(", "nextCommand", "!=", "null", ")", "{", "commitCommand", "(", "nextCommand", ".", "request", "(", ")", ",", "nextCommand", ".", "future", "(", ")", ")", ";", "session", ".", "setRequestSequence", "(", "nextSequence", ")", ";", "nextSequence", "=", "session", ".", "nextRequestSequence", "(", ")", ";", "nextCommand", "=", "session", ".", "removeCommand", "(", "nextSequence", ")", ";", "}", "}" ]
Sequentially drains pending commands from the session's command request queue. @param session the session for which to drain commands
[ "Sequentially", "drains", "pending", "commands", "from", "the", "session", "s", "command", "request", "queue", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java#L669-L688
27,478
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java
LeaderRole.commitCommand
private void commitCommand(CommandRequest request, CompletableFuture<CommandResponse> future) { final long term = raft.getTerm(); final long timestamp = System.currentTimeMillis(); CommandEntry command = new CommandEntry(term, timestamp, request.session(), request.sequenceNumber(), request.operation()); appendAndCompact(command) .whenCompleteAsync((entry, error) -> { if (error != null) { Throwable cause = Throwables.getRootCause(error); if (Throwables.getRootCause(error) instanceof StorageException.TooLarge) { log.warn("Failed to append command {}", command, cause); future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.PROTOCOL_ERROR) .build()); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } return; } // Replicate the command to followers. appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> { raft.checkThread(); if (isRunning()) { // If the command was successfully committed, apply it to the state machine. if (commitError == null) { raft.getServiceManager().<OperationResult>apply(entry.index()).whenComplete((r, e) -> { completeOperation(r, CommandResponse.builder(), e, future); }); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } }); }, raft.getThreadContext()); }
java
private void commitCommand(CommandRequest request, CompletableFuture<CommandResponse> future) { final long term = raft.getTerm(); final long timestamp = System.currentTimeMillis(); CommandEntry command = new CommandEntry(term, timestamp, request.session(), request.sequenceNumber(), request.operation()); appendAndCompact(command) .whenCompleteAsync((entry, error) -> { if (error != null) { Throwable cause = Throwables.getRootCause(error); if (Throwables.getRootCause(error) instanceof StorageException.TooLarge) { log.warn("Failed to append command {}", command, cause); future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.PROTOCOL_ERROR) .build()); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } return; } // Replicate the command to followers. appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> { raft.checkThread(); if (isRunning()) { // If the command was successfully committed, apply it to the state machine. if (commitError == null) { raft.getServiceManager().<OperationResult>apply(entry.index()).whenComplete((r, e) -> { completeOperation(r, CommandResponse.builder(), e, future); }); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } }); }, raft.getThreadContext()); }
[ "private", "void", "commitCommand", "(", "CommandRequest", "request", ",", "CompletableFuture", "<", "CommandResponse", ">", "future", ")", "{", "final", "long", "term", "=", "raft", ".", "getTerm", "(", ")", ";", "final", "long", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "CommandEntry", "command", "=", "new", "CommandEntry", "(", "term", ",", "timestamp", ",", "request", ".", "session", "(", ")", ",", "request", ".", "sequenceNumber", "(", ")", ",", "request", ".", "operation", "(", ")", ")", ";", "appendAndCompact", "(", "command", ")", ".", "whenCompleteAsync", "(", "(", "entry", ",", "error", ")", "->", "{", "if", "(", "error", "!=", "null", ")", "{", "Throwable", "cause", "=", "Throwables", ".", "getRootCause", "(", "error", ")", ";", "if", "(", "Throwables", ".", "getRootCause", "(", "error", ")", "instanceof", "StorageException", ".", "TooLarge", ")", "{", "log", ".", "warn", "(", "\"Failed to append command {}\"", ",", "command", ",", "cause", ")", ";", "future", ".", "complete", "(", "CommandResponse", ".", "builder", "(", ")", ".", "withStatus", "(", "RaftResponse", ".", "Status", ".", "ERROR", ")", ".", "withError", "(", "RaftError", ".", "Type", ".", "PROTOCOL_ERROR", ")", ".", "build", "(", ")", ")", ";", "}", "else", "{", "future", ".", "complete", "(", "CommandResponse", ".", "builder", "(", ")", ".", "withStatus", "(", "RaftResponse", ".", "Status", ".", "ERROR", ")", ".", "withError", "(", "RaftError", ".", "Type", ".", "COMMAND_FAILURE", ")", ".", "build", "(", ")", ")", ";", "}", "return", ";", "}", "// Replicate the command to followers.", "appender", ".", "appendEntries", "(", "entry", ".", "index", "(", ")", ")", ".", "whenComplete", "(", "(", "commitIndex", ",", "commitError", ")", "->", "{", "raft", ".", "checkThread", "(", ")", ";", "if", "(", "isRunning", "(", ")", ")", "{", "// If the command was successfully committed, apply it to the state machine.", "if", "(", "commitError", "==", "null", ")", "{", "raft", ".", "getServiceManager", "(", ")", ".", "<", "OperationResult", ">", "apply", "(", "entry", ".", "index", "(", ")", ")", ".", "whenComplete", "(", "(", "r", ",", "e", ")", "->", "{", "completeOperation", "(", "r", ",", "CommandResponse", ".", "builder", "(", ")", ",", "e", ",", "future", ")", ";", "}", ")", ";", "}", "else", "{", "future", ".", "complete", "(", "CommandResponse", ".", "builder", "(", ")", ".", "withStatus", "(", "RaftResponse", ".", "Status", ".", "ERROR", ")", ".", "withError", "(", "RaftError", ".", "Type", ".", "COMMAND_FAILURE", ")", ".", "build", "(", ")", ")", ";", "}", "}", "else", "{", "future", ".", "complete", "(", "CommandResponse", ".", "builder", "(", ")", ".", "withStatus", "(", "RaftResponse", ".", "Status", ".", "ERROR", ")", ".", "withError", "(", "RaftError", ".", "Type", ".", "COMMAND_FAILURE", ")", ".", "build", "(", ")", ")", ";", "}", "}", ")", ";", "}", ",", "raft", ".", "getThreadContext", "(", ")", ")", ";", "}" ]
Commits a command. @param request the command request @param future the command response future
[ "Commits", "a", "command", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java#L696-L743
27,479
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java
LeaderRole.failPendingCommands
private void failPendingCommands() { for (RaftSession session : raft.getSessions().getSessions()) { for (PendingCommand command : session.clearCommands()) { command.future().complete(logResponse(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE, "Request sequence number " + command.request().sequenceNumber() + " out of sequence") .withLastSequence(session.getRequestSequence()) .build())); } } }
java
private void failPendingCommands() { for (RaftSession session : raft.getSessions().getSessions()) { for (PendingCommand command : session.clearCommands()) { command.future().complete(logResponse(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE, "Request sequence number " + command.request().sequenceNumber() + " out of sequence") .withLastSequence(session.getRequestSequence()) .build())); } } }
[ "private", "void", "failPendingCommands", "(", ")", "{", "for", "(", "RaftSession", "session", ":", "raft", ".", "getSessions", "(", ")", ".", "getSessions", "(", ")", ")", "{", "for", "(", "PendingCommand", "command", ":", "session", ".", "clearCommands", "(", ")", ")", "{", "command", ".", "future", "(", ")", ".", "complete", "(", "logResponse", "(", "CommandResponse", ".", "builder", "(", ")", ".", "withStatus", "(", "RaftResponse", ".", "Status", ".", "ERROR", ")", ".", "withError", "(", "RaftError", ".", "Type", ".", "COMMAND_FAILURE", ",", "\"Request sequence number \"", "+", "command", ".", "request", "(", ")", ".", "sequenceNumber", "(", ")", "+", "\" out of sequence\"", ")", ".", "withLastSequence", "(", "session", ".", "getRequestSequence", "(", ")", ")", ".", "build", "(", ")", ")", ")", ";", "}", "}", "}" ]
Fails pending commands.
[ "Fails", "pending", "commands", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java#L1106-L1116
27,480
atomix/atomix
core/src/main/java/io/atomix/core/set/impl/SetUpdate.java
SetUpdate.map
public <T> SetUpdate<T> map(Function<E, T> mapper) { return new SetUpdate<T>(type, mapper.apply(element)); }
java
public <T> SetUpdate<T> map(Function<E, T> mapper) { return new SetUpdate<T>(type, mapper.apply(element)); }
[ "public", "<", "T", ">", "SetUpdate", "<", "T", ">", "map", "(", "Function", "<", "E", ",", "T", ">", "mapper", ")", "{", "return", "new", "SetUpdate", "<", "T", ">", "(", "type", ",", "mapper", ".", "apply", "(", "element", ")", ")", ";", "}" ]
Maps the value of the update to another type. @param mapper the mapper with which to transform the value @param <T> the type to which to transform the value @return the transformed set update
[ "Maps", "the", "value", "of", "the", "update", "to", "another", "type", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/set/impl/SetUpdate.java#L67-L69
27,481
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java
HeartbeatMembershipProtocol.handleDiscoveryEvent
private void handleDiscoveryEvent(NodeDiscoveryEvent event) { switch (event.type()) { case JOIN: handleJoinEvent(event.subject()); break; case LEAVE: handleLeaveEvent(event.subject()); break; default: throw new AssertionError(); } }
java
private void handleDiscoveryEvent(NodeDiscoveryEvent event) { switch (event.type()) { case JOIN: handleJoinEvent(event.subject()); break; case LEAVE: handleLeaveEvent(event.subject()); break; default: throw new AssertionError(); } }
[ "private", "void", "handleDiscoveryEvent", "(", "NodeDiscoveryEvent", "event", ")", "{", "switch", "(", "event", ".", "type", "(", ")", ")", "{", "case", "JOIN", ":", "handleJoinEvent", "(", "event", ".", "subject", "(", ")", ")", ";", "break", ";", "case", "LEAVE", ":", "handleLeaveEvent", "(", "event", ".", "subject", "(", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "AssertionError", "(", ")", ";", "}", "}" ]
Handles a member location event. @param event the member location event
[ "Handles", "a", "member", "location", "event", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java#L157-L168
27,482
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java
HeartbeatMembershipProtocol.sendHeartbeats
private CompletableFuture<Void> sendHeartbeats() { checkMetadata(); Stream<GossipMember> clusterMembers = members.values().stream() .filter(member -> !member.id().equals(localMember.id())); Stream<GossipMember> providerMembers = discoveryService.getNodes().stream() .filter(node -> !members.containsKey(MemberId.from(node.id().id()))) .map(node -> new GossipMember(MemberId.from(node.id().id()), node.address())); return Futures.allOf(Stream.concat(clusterMembers, providerMembers) .map(member -> { LOGGER.trace("{} - Sending heartbeat: {}", localMember.id(), member); return sendHeartbeat(member).exceptionally(v -> null); }).collect(Collectors.toList())) .thenApply(v -> null); }
java
private CompletableFuture<Void> sendHeartbeats() { checkMetadata(); Stream<GossipMember> clusterMembers = members.values().stream() .filter(member -> !member.id().equals(localMember.id())); Stream<GossipMember> providerMembers = discoveryService.getNodes().stream() .filter(node -> !members.containsKey(MemberId.from(node.id().id()))) .map(node -> new GossipMember(MemberId.from(node.id().id()), node.address())); return Futures.allOf(Stream.concat(clusterMembers, providerMembers) .map(member -> { LOGGER.trace("{} - Sending heartbeat: {}", localMember.id(), member); return sendHeartbeat(member).exceptionally(v -> null); }).collect(Collectors.toList())) .thenApply(v -> null); }
[ "private", "CompletableFuture", "<", "Void", ">", "sendHeartbeats", "(", ")", "{", "checkMetadata", "(", ")", ";", "Stream", "<", "GossipMember", ">", "clusterMembers", "=", "members", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "member", "->", "!", "member", ".", "id", "(", ")", ".", "equals", "(", "localMember", ".", "id", "(", ")", ")", ")", ";", "Stream", "<", "GossipMember", ">", "providerMembers", "=", "discoveryService", ".", "getNodes", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "node", "->", "!", "members", ".", "containsKey", "(", "MemberId", ".", "from", "(", "node", ".", "id", "(", ")", ".", "id", "(", ")", ")", ")", ")", ".", "map", "(", "node", "->", "new", "GossipMember", "(", "MemberId", ".", "from", "(", "node", ".", "id", "(", ")", ".", "id", "(", ")", ")", ",", "node", ".", "address", "(", ")", ")", ")", ";", "return", "Futures", ".", "allOf", "(", "Stream", ".", "concat", "(", "clusterMembers", ",", "providerMembers", ")", ".", "map", "(", "member", "->", "{", "LOGGER", ".", "trace", "(", "\"{} - Sending heartbeat: {}\"", ",", "localMember", ".", "id", "(", ")", ",", "member", ")", ";", "return", "sendHeartbeat", "(", "member", ")", ".", "exceptionally", "(", "v", "->", "null", ")", ";", "}", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}" ]
Sends heartbeats to all peers.
[ "Sends", "heartbeats", "to", "all", "peers", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java#L190-L205
27,483
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java
HeartbeatMembershipProtocol.sendHeartbeat
private CompletableFuture<Void> sendHeartbeat(GossipMember member) { return bootstrapService.getMessagingService().sendAndReceive(member.address(), HEARTBEAT_MESSAGE, SERIALIZER.encode(localMember)) .whenCompleteAsync((response, error) -> { if (error == null) { Collection<GossipMember> remoteMembers = SERIALIZER.decode(response); for (GossipMember remoteMember : remoteMembers) { if (!remoteMember.id().equals(localMember.id())) { updateMember(remoteMember, remoteMember.id().equals(member.id())); } } } else { LOGGER.debug("{} - Sending heartbeat to {} failed", localMember.id(), member, error); if (member.isReachable()) { member.setReachable(false); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, member)); } PhiAccrualFailureDetector failureDetector = failureDetectors.computeIfAbsent(member.id(), n -> new PhiAccrualFailureDetector()); double phi = failureDetector.phi(); if (phi >= config.getPhiFailureThreshold() || (phi == 0.0 && System.currentTimeMillis() - failureDetector.lastUpdated() > config.getFailureTimeout().toMillis())) { if (members.remove(member.id()) != null) { failureDetectors.remove(member.id()); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_REMOVED, member)); } } } }, heartbeatScheduler).exceptionally(e -> null) .thenApply(v -> null); }
java
private CompletableFuture<Void> sendHeartbeat(GossipMember member) { return bootstrapService.getMessagingService().sendAndReceive(member.address(), HEARTBEAT_MESSAGE, SERIALIZER.encode(localMember)) .whenCompleteAsync((response, error) -> { if (error == null) { Collection<GossipMember> remoteMembers = SERIALIZER.decode(response); for (GossipMember remoteMember : remoteMembers) { if (!remoteMember.id().equals(localMember.id())) { updateMember(remoteMember, remoteMember.id().equals(member.id())); } } } else { LOGGER.debug("{} - Sending heartbeat to {} failed", localMember.id(), member, error); if (member.isReachable()) { member.setReachable(false); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, member)); } PhiAccrualFailureDetector failureDetector = failureDetectors.computeIfAbsent(member.id(), n -> new PhiAccrualFailureDetector()); double phi = failureDetector.phi(); if (phi >= config.getPhiFailureThreshold() || (phi == 0.0 && System.currentTimeMillis() - failureDetector.lastUpdated() > config.getFailureTimeout().toMillis())) { if (members.remove(member.id()) != null) { failureDetectors.remove(member.id()); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_REMOVED, member)); } } } }, heartbeatScheduler).exceptionally(e -> null) .thenApply(v -> null); }
[ "private", "CompletableFuture", "<", "Void", ">", "sendHeartbeat", "(", "GossipMember", "member", ")", "{", "return", "bootstrapService", ".", "getMessagingService", "(", ")", ".", "sendAndReceive", "(", "member", ".", "address", "(", ")", ",", "HEARTBEAT_MESSAGE", ",", "SERIALIZER", ".", "encode", "(", "localMember", ")", ")", ".", "whenCompleteAsync", "(", "(", "response", ",", "error", ")", "->", "{", "if", "(", "error", "==", "null", ")", "{", "Collection", "<", "GossipMember", ">", "remoteMembers", "=", "SERIALIZER", ".", "decode", "(", "response", ")", ";", "for", "(", "GossipMember", "remoteMember", ":", "remoteMembers", ")", "{", "if", "(", "!", "remoteMember", ".", "id", "(", ")", ".", "equals", "(", "localMember", ".", "id", "(", ")", ")", ")", "{", "updateMember", "(", "remoteMember", ",", "remoteMember", ".", "id", "(", ")", ".", "equals", "(", "member", ".", "id", "(", ")", ")", ")", ";", "}", "}", "}", "else", "{", "LOGGER", ".", "debug", "(", "\"{} - Sending heartbeat to {} failed\"", ",", "localMember", ".", "id", "(", ")", ",", "member", ",", "error", ")", ";", "if", "(", "member", ".", "isReachable", "(", ")", ")", "{", "member", ".", "setReachable", "(", "false", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "REACHABILITY_CHANGED", ",", "member", ")", ")", ";", "}", "PhiAccrualFailureDetector", "failureDetector", "=", "failureDetectors", ".", "computeIfAbsent", "(", "member", ".", "id", "(", ")", ",", "n", "->", "new", "PhiAccrualFailureDetector", "(", ")", ")", ";", "double", "phi", "=", "failureDetector", ".", "phi", "(", ")", ";", "if", "(", "phi", ">=", "config", ".", "getPhiFailureThreshold", "(", ")", "||", "(", "phi", "==", "0.0", "&&", "System", ".", "currentTimeMillis", "(", ")", "-", "failureDetector", ".", "lastUpdated", "(", ")", ">", "config", ".", "getFailureTimeout", "(", ")", ".", "toMillis", "(", ")", ")", ")", "{", "if", "(", "members", ".", "remove", "(", "member", ".", "id", "(", ")", ")", "!=", "null", ")", "{", "failureDetectors", ".", "remove", "(", "member", ".", "id", "(", ")", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "MEMBER_REMOVED", ",", "member", ")", ")", ";", "}", "}", "}", "}", ",", "heartbeatScheduler", ")", ".", "exceptionally", "(", "e", "->", "null", ")", ".", "thenApply", "(", "v", "->", "null", ")", ";", "}" ]
Sends a heartbeat to the given peer.
[ "Sends", "a", "heartbeat", "to", "the", "given", "peer", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java#L221-L250
27,484
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java
HeartbeatMembershipProtocol.handleHeartbeat
private byte[] handleHeartbeat(Address address, byte[] message) { GossipMember remoteMember = SERIALIZER.decode(message); LOGGER.trace("{} - Received heartbeat: {}", localMember.id(), remoteMember); failureDetectors.computeIfAbsent(remoteMember.id(), n -> new PhiAccrualFailureDetector()).report(); updateMember(remoteMember, true); // Return only reachable members to avoid populating removed members on remote nodes from unreachable members. return SERIALIZER.encode(Lists.newArrayList(members.values() .stream() .filter(member -> member.isReachable()) .collect(Collectors.toList()))); }
java
private byte[] handleHeartbeat(Address address, byte[] message) { GossipMember remoteMember = SERIALIZER.decode(message); LOGGER.trace("{} - Received heartbeat: {}", localMember.id(), remoteMember); failureDetectors.computeIfAbsent(remoteMember.id(), n -> new PhiAccrualFailureDetector()).report(); updateMember(remoteMember, true); // Return only reachable members to avoid populating removed members on remote nodes from unreachable members. return SERIALIZER.encode(Lists.newArrayList(members.values() .stream() .filter(member -> member.isReachable()) .collect(Collectors.toList()))); }
[ "private", "byte", "[", "]", "handleHeartbeat", "(", "Address", "address", ",", "byte", "[", "]", "message", ")", "{", "GossipMember", "remoteMember", "=", "SERIALIZER", ".", "decode", "(", "message", ")", ";", "LOGGER", ".", "trace", "(", "\"{} - Received heartbeat: {}\"", ",", "localMember", ".", "id", "(", ")", ",", "remoteMember", ")", ";", "failureDetectors", ".", "computeIfAbsent", "(", "remoteMember", ".", "id", "(", ")", ",", "n", "->", "new", "PhiAccrualFailureDetector", "(", ")", ")", ".", "report", "(", ")", ";", "updateMember", "(", "remoteMember", ",", "true", ")", ";", "// Return only reachable members to avoid populating removed members on remote nodes from unreachable members.", "return", "SERIALIZER", ".", "encode", "(", "Lists", ".", "newArrayList", "(", "members", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "member", "->", "member", ".", "isReachable", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ")", ";", "}" ]
Handles a heartbeat message.
[ "Handles", "a", "heartbeat", "message", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java#L255-L266
27,485
atomix/atomix
cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java
HeartbeatMembershipProtocol.updateMember
private void updateMember(GossipMember remoteMember, boolean direct) { GossipMember localMember = members.get(remoteMember.id()); if (localMember == null) { remoteMember.setActive(true); remoteMember.setReachable(true); members.put(remoteMember.id(), remoteMember); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember)); } else if (!Objects.equals(localMember.version(), remoteMember.version())) { members.remove(localMember.id()); localMember.setReachable(false); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); localMember.setActive(false); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_REMOVED, localMember)); members.put(remoteMember.id(), remoteMember); remoteMember.setActive(true); remoteMember.setReachable(true); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember)); } else if (!Objects.equals(localMember.properties(), remoteMember.properties())) { if (!localMember.isReachable()) { localMember.setReachable(true); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); } localMember.properties().putAll(remoteMember.properties()); post(new GroupMembershipEvent(GroupMembershipEvent.Type.METADATA_CHANGED, localMember)); } else if (!localMember.isReachable() && direct) { localMember.setReachable(true); localMember.setTerm(localMember.getTerm() + 1); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); } else if (!localMember.isReachable() && remoteMember.getTerm() > localMember.getTerm()) { localMember.setReachable(true); localMember.setTerm(remoteMember.getTerm()); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); } }
java
private void updateMember(GossipMember remoteMember, boolean direct) { GossipMember localMember = members.get(remoteMember.id()); if (localMember == null) { remoteMember.setActive(true); remoteMember.setReachable(true); members.put(remoteMember.id(), remoteMember); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember)); } else if (!Objects.equals(localMember.version(), remoteMember.version())) { members.remove(localMember.id()); localMember.setReachable(false); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); localMember.setActive(false); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_REMOVED, localMember)); members.put(remoteMember.id(), remoteMember); remoteMember.setActive(true); remoteMember.setReachable(true); post(new GroupMembershipEvent(GroupMembershipEvent.Type.MEMBER_ADDED, remoteMember)); } else if (!Objects.equals(localMember.properties(), remoteMember.properties())) { if (!localMember.isReachable()) { localMember.setReachable(true); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); } localMember.properties().putAll(remoteMember.properties()); post(new GroupMembershipEvent(GroupMembershipEvent.Type.METADATA_CHANGED, localMember)); } else if (!localMember.isReachable() && direct) { localMember.setReachable(true); localMember.setTerm(localMember.getTerm() + 1); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); } else if (!localMember.isReachable() && remoteMember.getTerm() > localMember.getTerm()) { localMember.setReachable(true); localMember.setTerm(remoteMember.getTerm()); post(new GroupMembershipEvent(GroupMembershipEvent.Type.REACHABILITY_CHANGED, localMember)); } }
[ "private", "void", "updateMember", "(", "GossipMember", "remoteMember", ",", "boolean", "direct", ")", "{", "GossipMember", "localMember", "=", "members", ".", "get", "(", "remoteMember", ".", "id", "(", ")", ")", ";", "if", "(", "localMember", "==", "null", ")", "{", "remoteMember", ".", "setActive", "(", "true", ")", ";", "remoteMember", ".", "setReachable", "(", "true", ")", ";", "members", ".", "put", "(", "remoteMember", ".", "id", "(", ")", ",", "remoteMember", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "MEMBER_ADDED", ",", "remoteMember", ")", ")", ";", "}", "else", "if", "(", "!", "Objects", ".", "equals", "(", "localMember", ".", "version", "(", ")", ",", "remoteMember", ".", "version", "(", ")", ")", ")", "{", "members", ".", "remove", "(", "localMember", ".", "id", "(", ")", ")", ";", "localMember", ".", "setReachable", "(", "false", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "REACHABILITY_CHANGED", ",", "localMember", ")", ")", ";", "localMember", ".", "setActive", "(", "false", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "MEMBER_REMOVED", ",", "localMember", ")", ")", ";", "members", ".", "put", "(", "remoteMember", ".", "id", "(", ")", ",", "remoteMember", ")", ";", "remoteMember", ".", "setActive", "(", "true", ")", ";", "remoteMember", ".", "setReachable", "(", "true", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "MEMBER_ADDED", ",", "remoteMember", ")", ")", ";", "}", "else", "if", "(", "!", "Objects", ".", "equals", "(", "localMember", ".", "properties", "(", ")", ",", "remoteMember", ".", "properties", "(", ")", ")", ")", "{", "if", "(", "!", "localMember", ".", "isReachable", "(", ")", ")", "{", "localMember", ".", "setReachable", "(", "true", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "REACHABILITY_CHANGED", ",", "localMember", ")", ")", ";", "}", "localMember", ".", "properties", "(", ")", ".", "putAll", "(", "remoteMember", ".", "properties", "(", ")", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "METADATA_CHANGED", ",", "localMember", ")", ")", ";", "}", "else", "if", "(", "!", "localMember", ".", "isReachable", "(", ")", "&&", "direct", ")", "{", "localMember", ".", "setReachable", "(", "true", ")", ";", "localMember", ".", "setTerm", "(", "localMember", ".", "getTerm", "(", ")", "+", "1", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "REACHABILITY_CHANGED", ",", "localMember", ")", ")", ";", "}", "else", "if", "(", "!", "localMember", ".", "isReachable", "(", ")", "&&", "remoteMember", ".", "getTerm", "(", ")", ">", "localMember", ".", "getTerm", "(", ")", ")", "{", "localMember", ".", "setReachable", "(", "true", ")", ";", "localMember", ".", "setTerm", "(", "remoteMember", ".", "getTerm", "(", ")", ")", ";", "post", "(", "new", "GroupMembershipEvent", "(", "GroupMembershipEvent", ".", "Type", ".", "REACHABILITY_CHANGED", ",", "localMember", ")", ")", ";", "}", "}" ]
Updates the state of the given member. @param remoteMember the member received from a remote node @param direct whether this is a direct update
[ "Updates", "the", "state", "of", "the", "given", "member", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/protocol/HeartbeatMembershipProtocol.java#L274-L307
27,486
atomix/atomix
cluster/src/main/java/io/atomix/cluster/NodeConfig.java
NodeConfig.setAddress
@Deprecated public NodeConfig setAddress(Address address) { this.host = address.host(); this.port = address.port(); return this; }
java
@Deprecated public NodeConfig setAddress(Address address) { this.host = address.host(); this.port = address.port(); return this; }
[ "@", "Deprecated", "public", "NodeConfig", "setAddress", "(", "Address", "address", ")", "{", "this", ".", "host", "=", "address", ".", "host", "(", ")", ";", "this", ".", "port", "=", "address", ".", "port", "(", ")", ";", "return", "this", ";", "}" ]
Sets the node address. @param address the node address @return the node configuration
[ "Sets", "the", "node", "address", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/NodeConfig.java#L125-L130
27,487
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/UpdateEntry.java
UpdateEntry.isNewerThan
public boolean isNewerThan(UpdateEntry other) { return other == null || other.value == null || (value != null && value.isNewerThan(other.value)); }
java
public boolean isNewerThan(UpdateEntry other) { return other == null || other.value == null || (value != null && value.isNewerThan(other.value)); }
[ "public", "boolean", "isNewerThan", "(", "UpdateEntry", "other", ")", "{", "return", "other", "==", "null", "||", "other", ".", "value", "==", "null", "||", "(", "value", "!=", "null", "&&", "value", ".", "isNewerThan", "(", "other", ".", "value", ")", ")", ";", "}" ]
Returns if this entry is newer than other entry. @param other other entry @return true if this entry is newer; false otherwise
[ "Returns", "if", "this", "entry", "is", "newer", "than", "other", "entry", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/UpdateEntry.java#L64-L66
27,488
atomix/atomix
core/src/main/java/io/atomix/core/tree/DocumentPath.java
DocumentPath.childPath
public DocumentPath childPath() { if (pathElements.size() <= 1) { return null; } return new DocumentPath(this.pathElements.subList(pathElements.size() - 1, pathElements.size())); }
java
public DocumentPath childPath() { if (pathElements.size() <= 1) { return null; } return new DocumentPath(this.pathElements.subList(pathElements.size() - 1, pathElements.size())); }
[ "public", "DocumentPath", "childPath", "(", ")", "{", "if", "(", "pathElements", ".", "size", "(", ")", "<=", "1", ")", "{", "return", "null", ";", "}", "return", "new", "DocumentPath", "(", "this", ".", "pathElements", ".", "subList", "(", "pathElements", ".", "size", "(", ")", "-", "1", ",", "pathElements", ".", "size", "(", ")", ")", ")", ";", "}" ]
Returns the relative path to the given node. @return relative path to the given node.
[ "Returns", "the", "relative", "path", "to", "the", "given", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/tree/DocumentPath.java#L151-L156
27,489
atomix/atomix
core/src/main/java/io/atomix/core/tree/DocumentPath.java
DocumentPath.parent
public DocumentPath parent() { if (pathElements.size() <= 1) { return null; } return new DocumentPath(this.pathElements.subList(0, pathElements.size() - 1)); }
java
public DocumentPath parent() { if (pathElements.size() <= 1) { return null; } return new DocumentPath(this.pathElements.subList(0, pathElements.size() - 1)); }
[ "public", "DocumentPath", "parent", "(", ")", "{", "if", "(", "pathElements", ".", "size", "(", ")", "<=", "1", ")", "{", "return", "null", ";", "}", "return", "new", "DocumentPath", "(", "this", ".", "pathElements", ".", "subList", "(", "0", ",", "pathElements", ".", "size", "(", ")", "-", "1", ")", ")", ";", "}" ]
Returns a path for the parent of this node. @return parent node path. If this path is for the root, returns {@code null}.
[ "Returns", "a", "path", "for", "the", "parent", "of", "this", "node", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/tree/DocumentPath.java#L163-L168
27,490
atomix/atomix
core/src/main/java/io/atomix/core/tree/DocumentPath.java
DocumentPath.leastCommonAncestor
public static DocumentPath leastCommonAncestor(Collection<DocumentPath> paths) { if (paths.isEmpty()) { return null; } return DocumentPath.from(StringUtils.getCommonPrefix(paths.stream() .map(DocumentPath::toString) .toArray(String[]::new))); }
java
public static DocumentPath leastCommonAncestor(Collection<DocumentPath> paths) { if (paths.isEmpty()) { return null; } return DocumentPath.from(StringUtils.getCommonPrefix(paths.stream() .map(DocumentPath::toString) .toArray(String[]::new))); }
[ "public", "static", "DocumentPath", "leastCommonAncestor", "(", "Collection", "<", "DocumentPath", ">", "paths", ")", "{", "if", "(", "paths", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "DocumentPath", ".", "from", "(", "StringUtils", ".", "getCommonPrefix", "(", "paths", ".", "stream", "(", ")", ".", "map", "(", "DocumentPath", "::", "toString", ")", ".", "toArray", "(", "String", "[", "]", "::", "new", ")", ")", ")", ";", "}" ]
Returns the path that points to the least common ancestor of the specified collection of paths. @param paths collection of path @return path to least common ancestor
[ "Returns", "the", "path", "that", "points", "to", "the", "least", "common", "ancestor", "of", "the", "specified", "collection", "of", "paths", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/tree/DocumentPath.java#L212-L219
27,491
atomix/atomix
utils/src/main/java/io/atomix/utils/misc/SlidingWindowCounter.java
SlidingWindowCounter.get
public long get(int slots) { checkArgument(slots <= windowSlots, "Requested window must be less than the total window slots"); long sum = 0; for (int i = 0; i < slots; i++) { int currentIndex = headSlot - i; if (currentIndex < 0) { currentIndex = counters.size() + currentIndex; } sum += counters.get(currentIndex).get(); } return sum; }
java
public long get(int slots) { checkArgument(slots <= windowSlots, "Requested window must be less than the total window slots"); long sum = 0; for (int i = 0; i < slots; i++) { int currentIndex = headSlot - i; if (currentIndex < 0) { currentIndex = counters.size() + currentIndex; } sum += counters.get(currentIndex).get(); } return sum; }
[ "public", "long", "get", "(", "int", "slots", ")", "{", "checkArgument", "(", "slots", "<=", "windowSlots", ",", "\"Requested window must be less than the total window slots\"", ")", ";", "long", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "slots", ";", "i", "++", ")", "{", "int", "currentIndex", "=", "headSlot", "-", "i", ";", "if", "(", "currentIndex", "<", "0", ")", "{", "currentIndex", "=", "counters", ".", "size", "(", ")", "+", "currentIndex", ";", "}", "sum", "+=", "counters", ".", "get", "(", "currentIndex", ")", ".", "get", "(", ")", ";", "}", "return", "sum", ";", "}" ]
Gets the total count for the last N window slots. @param slots number of slots to include in the count @return total count for last N slots
[ "Gets", "the", "total", "count", "for", "the", "last", "N", "window", "slots", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/misc/SlidingWindowCounter.java#L108-L123
27,492
atomix/atomix
core/src/main/java/io/atomix/core/election/Leader.java
Leader.map
public <U> Leader<U> map(Function<T, U> mapper) { return new Leader<>(mapper.apply(id), term, termStartTime); }
java
public <U> Leader<U> map(Function<T, U> mapper) { return new Leader<>(mapper.apply(id), term, termStartTime); }
[ "public", "<", "U", ">", "Leader", "<", "U", ">", "map", "(", "Function", "<", "T", ",", "U", ">", "mapper", ")", "{", "return", "new", "Leader", "<>", "(", "mapper", ".", "apply", "(", "id", ")", ",", "term", ",", "termStartTime", ")", ";", "}" ]
Converts the leader identifier using the given mapping function. @param mapper the mapping function with which to convert the identifier @param <U> the converted type @return the converted leader object
[ "Converts", "the", "leader", "identifier", "using", "the", "given", "mapping", "function", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/election/Leader.java#L83-L85
27,493
atomix/atomix
core/src/main/java/io/atomix/core/election/Leadership.java
Leadership.map
public <U> Leadership<U> map(Function<T, U> mapper) { return new Leadership<>( leader != null ? leader.map(mapper) : null, candidates.stream().map(mapper).collect(Collectors.toList())); }
java
public <U> Leadership<U> map(Function<T, U> mapper) { return new Leadership<>( leader != null ? leader.map(mapper) : null, candidates.stream().map(mapper).collect(Collectors.toList())); }
[ "public", "<", "U", ">", "Leadership", "<", "U", ">", "map", "(", "Function", "<", "T", ",", "U", ">", "mapper", ")", "{", "return", "new", "Leadership", "<>", "(", "leader", "!=", "null", "?", "leader", ".", "map", "(", "mapper", ")", ":", "null", ",", "candidates", ".", "stream", "(", ")", ".", "map", "(", "mapper", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "}" ]
Maps the leadership identifiers using the given mapper. @param mapper the mapper with which to convert identifiers @param <U> the converted identifier type @return the converted leadership
[ "Maps", "the", "leadership", "identifiers", "using", "the", "given", "mapper", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/election/Leadership.java#L70-L74
27,494
atomix/atomix
protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogSession.java
DistributedLogSession.changeState
private synchronized void changeState(PrimitiveState state) { if (this.state != state) { this.state = state; stateChangeListeners.forEach(l -> threadContext.execute(() -> l.accept(state))); } }
java
private synchronized void changeState(PrimitiveState state) { if (this.state != state) { this.state = state; stateChangeListeners.forEach(l -> threadContext.execute(() -> l.accept(state))); } }
[ "private", "synchronized", "void", "changeState", "(", "PrimitiveState", "state", ")", "{", "if", "(", "this", ".", "state", "!=", "state", ")", "{", "this", ".", "state", "=", "state", ";", "stateChangeListeners", ".", "forEach", "(", "l", "->", "threadContext", ".", "execute", "(", "(", ")", "->", "l", ".", "accept", "(", "state", ")", ")", ")", ";", "}", "}" ]
Changes the current session state. @param state the updated session state
[ "Changes", "the", "current", "session", "state", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogSession.java#L153-L158
27,495
atomix/atomix
protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogSession.java
DistributedLogSession.term
private CompletableFuture<PrimaryTerm> term() { CompletableFuture<PrimaryTerm> future = new CompletableFuture<>(); threadContext.execute(() -> { if (term != null) { future.complete(term); } else { primaryElection.getTerm().whenCompleteAsync((term, error) -> { if (term != null) { this.term = term; future.complete(term); } else { future.completeExceptionally(new PrimitiveException.Unavailable()); } }); } }); return future; }
java
private CompletableFuture<PrimaryTerm> term() { CompletableFuture<PrimaryTerm> future = new CompletableFuture<>(); threadContext.execute(() -> { if (term != null) { future.complete(term); } else { primaryElection.getTerm().whenCompleteAsync((term, error) -> { if (term != null) { this.term = term; future.complete(term); } else { future.completeExceptionally(new PrimitiveException.Unavailable()); } }); } }); return future; }
[ "private", "CompletableFuture", "<", "PrimaryTerm", ">", "term", "(", ")", "{", "CompletableFuture", "<", "PrimaryTerm", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "threadContext", ".", "execute", "(", "(", ")", "->", "{", "if", "(", "term", "!=", "null", ")", "{", "future", ".", "complete", "(", "term", ")", ";", "}", "else", "{", "primaryElection", ".", "getTerm", "(", ")", ".", "whenCompleteAsync", "(", "(", "term", ",", "error", ")", "->", "{", "if", "(", "term", "!=", "null", ")", "{", "this", ".", "term", "=", "term", ";", "future", ".", "complete", "(", "term", ")", ";", "}", "else", "{", "future", ".", "completeExceptionally", "(", "new", "PrimitiveException", ".", "Unavailable", "(", ")", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "return", "future", ";", "}" ]
Returns the current primary term. @return the current primary term
[ "Returns", "the", "current", "primary", "term", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/log/src/main/java/io/atomix/protocols/log/impl/DistributedLogSession.java#L192-L209
27,496
atomix/atomix
core/src/main/java/io/atomix/core/Atomix.java
Atomix.buildSystemPartitionGroup
@SuppressWarnings("unchecked") private static ManagedPartitionGroup buildSystemPartitionGroup(AtomixConfig config) { PartitionGroupConfig<?> partitionGroupConfig = config.getManagementGroup(); if (partitionGroupConfig == null) { return null; } return partitionGroupConfig.getType().newPartitionGroup(partitionGroupConfig); }
java
@SuppressWarnings("unchecked") private static ManagedPartitionGroup buildSystemPartitionGroup(AtomixConfig config) { PartitionGroupConfig<?> partitionGroupConfig = config.getManagementGroup(); if (partitionGroupConfig == null) { return null; } return partitionGroupConfig.getType().newPartitionGroup(partitionGroupConfig); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "ManagedPartitionGroup", "buildSystemPartitionGroup", "(", "AtomixConfig", "config", ")", "{", "PartitionGroupConfig", "<", "?", ">", "partitionGroupConfig", "=", "config", ".", "getManagementGroup", "(", ")", ";", "if", "(", "partitionGroupConfig", "==", "null", ")", "{", "return", "null", ";", "}", "return", "partitionGroupConfig", ".", "getType", "(", ")", ".", "newPartitionGroup", "(", "partitionGroupConfig", ")", ";", "}" ]
Builds the core partition group.
[ "Builds", "the", "core", "partition", "group", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/Atomix.java#L898-L905
27,497
atomix/atomix
core/src/main/java/io/atomix/core/Atomix.java
Atomix.buildPartitionService
@SuppressWarnings("unchecked") private static ManagedPartitionService buildPartitionService( AtomixConfig config, ClusterMembershipService clusterMembershipService, ClusterCommunicationService messagingService, AtomixRegistry registry) { List<ManagedPartitionGroup> partitionGroups = new ArrayList<>(); for (PartitionGroupConfig<?> partitionGroupConfig : config.getPartitionGroups().values()) { partitionGroups.add(partitionGroupConfig.getType().newPartitionGroup(partitionGroupConfig)); } return new DefaultPartitionService( clusterMembershipService, messagingService, new DefaultPrimitiveTypeRegistry(registry.getTypes(PrimitiveType.class)), buildSystemPartitionGroup(config), partitionGroups, new DefaultPartitionGroupTypeRegistry(registry.getTypes(PartitionGroup.Type.class))); }
java
@SuppressWarnings("unchecked") private static ManagedPartitionService buildPartitionService( AtomixConfig config, ClusterMembershipService clusterMembershipService, ClusterCommunicationService messagingService, AtomixRegistry registry) { List<ManagedPartitionGroup> partitionGroups = new ArrayList<>(); for (PartitionGroupConfig<?> partitionGroupConfig : config.getPartitionGroups().values()) { partitionGroups.add(partitionGroupConfig.getType().newPartitionGroup(partitionGroupConfig)); } return new DefaultPartitionService( clusterMembershipService, messagingService, new DefaultPrimitiveTypeRegistry(registry.getTypes(PrimitiveType.class)), buildSystemPartitionGroup(config), partitionGroups, new DefaultPartitionGroupTypeRegistry(registry.getTypes(PartitionGroup.Type.class))); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "ManagedPartitionService", "buildPartitionService", "(", "AtomixConfig", "config", ",", "ClusterMembershipService", "clusterMembershipService", ",", "ClusterCommunicationService", "messagingService", ",", "AtomixRegistry", "registry", ")", "{", "List", "<", "ManagedPartitionGroup", ">", "partitionGroups", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "PartitionGroupConfig", "<", "?", ">", "partitionGroupConfig", ":", "config", ".", "getPartitionGroups", "(", ")", ".", "values", "(", ")", ")", "{", "partitionGroups", ".", "add", "(", "partitionGroupConfig", ".", "getType", "(", ")", ".", "newPartitionGroup", "(", "partitionGroupConfig", ")", ")", ";", "}", "return", "new", "DefaultPartitionService", "(", "clusterMembershipService", ",", "messagingService", ",", "new", "DefaultPrimitiveTypeRegistry", "(", "registry", ".", "getTypes", "(", "PrimitiveType", ".", "class", ")", ")", ",", "buildSystemPartitionGroup", "(", "config", ")", ",", "partitionGroups", ",", "new", "DefaultPartitionGroupTypeRegistry", "(", "registry", ".", "getTypes", "(", "PartitionGroup", ".", "Type", ".", "class", ")", ")", ")", ";", "}" ]
Builds a partition service.
[ "Builds", "a", "partition", "service", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/Atomix.java#L910-L928
27,498
atomix/atomix
primitive/src/main/java/io/atomix/primitive/PrimitiveId.java
PrimitiveId.from
public static PrimitiveId from(String id) { return from(Hashing.sha256().hashString(id, StandardCharsets.UTF_8).asLong()); }
java
public static PrimitiveId from(String id) { return from(Hashing.sha256().hashString(id, StandardCharsets.UTF_8).asLong()); }
[ "public", "static", "PrimitiveId", "from", "(", "String", "id", ")", "{", "return", "from", "(", "Hashing", ".", "sha256", "(", ")", ".", "hashString", "(", "id", ",", "StandardCharsets", ".", "UTF_8", ")", ".", "asLong", "(", ")", ")", ";", "}" ]
Creates a snapshot ID from the given string. @param id the string from which to create the identifier @return the snapshot identifier
[ "Creates", "a", "snapshot", "ID", "from", "the", "given", "string", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/primitive/src/main/java/io/atomix/primitive/PrimitiveId.java#L44-L46
27,499
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/FileSnapshot.java
FileSnapshot.delete
@Override public void delete() { LOGGER.debug("Deleting {}", this); Path path = file.file().toPath(); if (Files.exists(path)) { try { Files.delete(file.file().toPath()); } catch (IOException e) { } } }
java
@Override public void delete() { LOGGER.debug("Deleting {}", this); Path path = file.file().toPath(); if (Files.exists(path)) { try { Files.delete(file.file().toPath()); } catch (IOException e) { } } }
[ "@", "Override", "public", "void", "delete", "(", ")", "{", "LOGGER", ".", "debug", "(", "\"Deleting {}\"", ",", "this", ")", ";", "Path", "path", "=", "file", ".", "file", "(", ")", ".", "toPath", "(", ")", ";", "if", "(", "Files", ".", "exists", "(", "path", ")", ")", "{", "try", "{", "Files", ".", "delete", "(", "file", ".", "file", "(", ")", ".", "toPath", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "}", "}", "}" ]
Deletes the snapshot file.
[ "Deletes", "the", "snapshot", "file", "." ]
3a94b7c80576d762dd0d396d4645df07a0b37c31
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/FileSnapshot.java#L85-L95