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
15,500
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.updateLocalKeyLoadStatus
private void updateLocalKeyLoadStatus(Throwable t) { Operation op = new KeyLoadStatusOperation(mapName, t); // This updates the local record store on the partition thread. // If invoked by the SENDER_BACKUP however it's the replica index has to be set to 1, otherwise // it will be a remote call to the SENDER who is the owner of the given partitionId. if (hasBackup && role.is(Role.SENDER_BACKUP)) { opService.createInvocationBuilder(SERVICE_NAME, op, partitionId).setReplicaIndex(1).invoke(); } else { opService.createInvocationBuilder(SERVICE_NAME, op, partitionId).invoke(); } }
java
private void updateLocalKeyLoadStatus(Throwable t) { Operation op = new KeyLoadStatusOperation(mapName, t); // This updates the local record store on the partition thread. // If invoked by the SENDER_BACKUP however it's the replica index has to be set to 1, otherwise // it will be a remote call to the SENDER who is the owner of the given partitionId. if (hasBackup && role.is(Role.SENDER_BACKUP)) { opService.createInvocationBuilder(SERVICE_NAME, op, partitionId).setReplicaIndex(1).invoke(); } else { opService.createInvocationBuilder(SERVICE_NAME, op, partitionId).invoke(); } }
[ "private", "void", "updateLocalKeyLoadStatus", "(", "Throwable", "t", ")", "{", "Operation", "op", "=", "new", "KeyLoadStatusOperation", "(", "mapName", ",", "t", ")", ";", "// This updates the local record store on the partition thread.", "// If invoked by the SENDER_BACKUP however it's the replica index has to be set to 1, otherwise", "// it will be a remote call to the SENDER who is the owner of the given partitionId.", "if", "(", "hasBackup", "&&", "role", ".", "is", "(", "Role", ".", "SENDER_BACKUP", ")", ")", "{", "opService", ".", "createInvocationBuilder", "(", "SERVICE_NAME", ",", "op", ",", "partitionId", ")", ".", "setReplicaIndex", "(", "1", ")", ".", "invoke", "(", ")", ";", "}", "else", "{", "opService", ".", "createInvocationBuilder", "(", "SERVICE_NAME", ",", "op", ",", "partitionId", ")", ".", "invoke", "(", ")", ";", "}", "}" ]
Notifies the record store of this map key loader that key loading has completed. @param t an exception that occurred during key loading or {@code null} if there was no exception
[ "Notifies", "the", "record", "store", "of", "this", "map", "key", "loader", "that", "key", "loading", "has", "completed", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L304-L314
15,501
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.startLoading
public Future<?> startLoading(MapStoreContext mapStoreContext, boolean replaceExistingValues) { role.nextOrStay(Role.SENDER); if (state.is(State.LOADING)) { return keyLoadFinished; } state.next(State.LOADING); return sendKeys(mapStoreContext, replaceExistingValues); }
java
public Future<?> startLoading(MapStoreContext mapStoreContext, boolean replaceExistingValues) { role.nextOrStay(Role.SENDER); if (state.is(State.LOADING)) { return keyLoadFinished; } state.next(State.LOADING); return sendKeys(mapStoreContext, replaceExistingValues); }
[ "public", "Future", "<", "?", ">", "startLoading", "(", "MapStoreContext", "mapStoreContext", ",", "boolean", "replaceExistingValues", ")", "{", "role", ".", "nextOrStay", "(", "Role", ".", "SENDER", ")", ";", "if", "(", "state", ".", "is", "(", "State", ".", "LOADING", ")", ")", "{", "return", "keyLoadFinished", ";", "}", "state", ".", "next", "(", "State", ".", "LOADING", ")", ";", "return", "sendKeys", "(", "mapStoreContext", ",", "replaceExistingValues", ")", ";", "}" ]
Triggers key and value loading if there is no ongoing or completed key loading task, otherwise does nothing. The actual loading is done on a separate thread. @param mapStoreContext the map store context for this map @param replaceExistingValues if the existing entries for the loaded keys should be replaced @return a future representing pending completion of the key loading task
[ "Triggers", "key", "and", "value", "loading", "if", "there", "is", "no", "ongoing", "or", "completed", "key", "loading", "task", "otherwise", "does", "nothing", ".", "The", "actual", "loading", "is", "done", "on", "a", "separate", "thread", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L325-L334
15,502
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.triggerLoadingWithDelay
public void triggerLoadingWithDelay() { if (delayedTrigger == null) { Runnable runnable = () -> { Operation op = new TriggerLoadIfNeededOperation(mapName); opService.invokeOnPartition(SERVICE_NAME, op, mapNamePartition); }; delayedTrigger = new CoalescingDelayedTrigger(execService, LOADING_TRIGGER_DELAY, LOADING_TRIGGER_DELAY, runnable); } delayedTrigger.executeWithDelay(); }
java
public void triggerLoadingWithDelay() { if (delayedTrigger == null) { Runnable runnable = () -> { Operation op = new TriggerLoadIfNeededOperation(mapName); opService.invokeOnPartition(SERVICE_NAME, op, mapNamePartition); }; delayedTrigger = new CoalescingDelayedTrigger(execService, LOADING_TRIGGER_DELAY, LOADING_TRIGGER_DELAY, runnable); } delayedTrigger.executeWithDelay(); }
[ "public", "void", "triggerLoadingWithDelay", "(", ")", "{", "if", "(", "delayedTrigger", "==", "null", ")", "{", "Runnable", "runnable", "=", "(", ")", "->", "{", "Operation", "op", "=", "new", "TriggerLoadIfNeededOperation", "(", "mapName", ")", ";", "opService", ".", "invokeOnPartition", "(", "SERVICE_NAME", ",", "op", ",", "mapNamePartition", ")", ";", "}", ";", "delayedTrigger", "=", "new", "CoalescingDelayedTrigger", "(", "execService", ",", "LOADING_TRIGGER_DELAY", ",", "LOADING_TRIGGER_DELAY", ",", "runnable", ")", ";", "}", "delayedTrigger", ".", "executeWithDelay", "(", ")", ";", "}" ]
Triggers key loading on SENDER if it hadn't started. Delays triggering if invoked multiple times.
[ "Triggers", "key", "loading", "on", "SENDER", "if", "it", "hadn", "t", "started", ".", "Delays", "triggering", "if", "invoked", "multiple", "times", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L362-L372
15,503
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.sendKeysInBatches
private void sendKeysInBatches(MapStoreContext mapStoreContext, boolean replaceExistingValues) throws Exception { if (logger.isFinestEnabled()) { logger.finest("sendKeysInBatches invoked " + getStateMessage()); } int clusterSize = partitionService.getMemberPartitionsMap().size(); Iterator<Object> keys = null; Throwable loadError = null; try { Iterable<Object> allKeys = mapStoreContext.loadAllKeys(); keys = allKeys.iterator(); Iterator<Data> dataKeys = map(keys, toData); int mapMaxSize = clusterSize * maxSizePerNode; if (mapMaxSize > 0) { dataKeys = limit(dataKeys, mapMaxSize); } Iterator<Entry<Integer, Data>> partitionsAndKeys = map(dataKeys, toPartition(partitionService)); Iterator<Map<Integer, List<Data>>> batches = toBatches(partitionsAndKeys, maxBatch); List<Future> futures = new ArrayList<>(); while (batches.hasNext()) { Map<Integer, List<Data>> batch = batches.next(); futures.addAll(sendBatch(batch, replaceExistingValues)); } // This acts as a barrier to prevent re-ordering of key distribution operations (LoadAllOperation) // and LoadStatusOperation(s) which indicates all keys were already loaded. // Re-ordering of in-flight operations can happen during a partition migration. We are waiting here // for all LoadAllOperation(s) to be ACKed by receivers and only then we send them the LoadStatusOperation // See https://github.com/hazelcast/hazelcast/issues/4024 for additional details FutureUtil.waitForever(futures); } catch (Exception caught) { loadError = caught; } finally { sendKeyLoadCompleted(clusterSize, loadError); if (keys instanceof Closeable) { closeResource((Closeable) keys); } } }
java
private void sendKeysInBatches(MapStoreContext mapStoreContext, boolean replaceExistingValues) throws Exception { if (logger.isFinestEnabled()) { logger.finest("sendKeysInBatches invoked " + getStateMessage()); } int clusterSize = partitionService.getMemberPartitionsMap().size(); Iterator<Object> keys = null; Throwable loadError = null; try { Iterable<Object> allKeys = mapStoreContext.loadAllKeys(); keys = allKeys.iterator(); Iterator<Data> dataKeys = map(keys, toData); int mapMaxSize = clusterSize * maxSizePerNode; if (mapMaxSize > 0) { dataKeys = limit(dataKeys, mapMaxSize); } Iterator<Entry<Integer, Data>> partitionsAndKeys = map(dataKeys, toPartition(partitionService)); Iterator<Map<Integer, List<Data>>> batches = toBatches(partitionsAndKeys, maxBatch); List<Future> futures = new ArrayList<>(); while (batches.hasNext()) { Map<Integer, List<Data>> batch = batches.next(); futures.addAll(sendBatch(batch, replaceExistingValues)); } // This acts as a barrier to prevent re-ordering of key distribution operations (LoadAllOperation) // and LoadStatusOperation(s) which indicates all keys were already loaded. // Re-ordering of in-flight operations can happen during a partition migration. We are waiting here // for all LoadAllOperation(s) to be ACKed by receivers and only then we send them the LoadStatusOperation // See https://github.com/hazelcast/hazelcast/issues/4024 for additional details FutureUtil.waitForever(futures); } catch (Exception caught) { loadError = caught; } finally { sendKeyLoadCompleted(clusterSize, loadError); if (keys instanceof Closeable) { closeResource((Closeable) keys); } } }
[ "private", "void", "sendKeysInBatches", "(", "MapStoreContext", "mapStoreContext", ",", "boolean", "replaceExistingValues", ")", "throws", "Exception", "{", "if", "(", "logger", ".", "isFinestEnabled", "(", ")", ")", "{", "logger", ".", "finest", "(", "\"sendKeysInBatches invoked \"", "+", "getStateMessage", "(", ")", ")", ";", "}", "int", "clusterSize", "=", "partitionService", ".", "getMemberPartitionsMap", "(", ")", ".", "size", "(", ")", ";", "Iterator", "<", "Object", ">", "keys", "=", "null", ";", "Throwable", "loadError", "=", "null", ";", "try", "{", "Iterable", "<", "Object", ">", "allKeys", "=", "mapStoreContext", ".", "loadAllKeys", "(", ")", ";", "keys", "=", "allKeys", ".", "iterator", "(", ")", ";", "Iterator", "<", "Data", ">", "dataKeys", "=", "map", "(", "keys", ",", "toData", ")", ";", "int", "mapMaxSize", "=", "clusterSize", "*", "maxSizePerNode", ";", "if", "(", "mapMaxSize", ">", "0", ")", "{", "dataKeys", "=", "limit", "(", "dataKeys", ",", "mapMaxSize", ")", ";", "}", "Iterator", "<", "Entry", "<", "Integer", ",", "Data", ">", ">", "partitionsAndKeys", "=", "map", "(", "dataKeys", ",", "toPartition", "(", "partitionService", ")", ")", ";", "Iterator", "<", "Map", "<", "Integer", ",", "List", "<", "Data", ">", ">", ">", "batches", "=", "toBatches", "(", "partitionsAndKeys", ",", "maxBatch", ")", ";", "List", "<", "Future", ">", "futures", "=", "new", "ArrayList", "<>", "(", ")", ";", "while", "(", "batches", ".", "hasNext", "(", ")", ")", "{", "Map", "<", "Integer", ",", "List", "<", "Data", ">", ">", "batch", "=", "batches", ".", "next", "(", ")", ";", "futures", ".", "addAll", "(", "sendBatch", "(", "batch", ",", "replaceExistingValues", ")", ")", ";", "}", "// This acts as a barrier to prevent re-ordering of key distribution operations (LoadAllOperation)", "// and LoadStatusOperation(s) which indicates all keys were already loaded.", "// Re-ordering of in-flight operations can happen during a partition migration. We are waiting here", "// for all LoadAllOperation(s) to be ACKed by receivers and only then we send them the LoadStatusOperation", "// See https://github.com/hazelcast/hazelcast/issues/4024 for additional details", "FutureUtil", ".", "waitForever", "(", "futures", ")", ";", "}", "catch", "(", "Exception", "caught", ")", "{", "loadError", "=", "caught", ";", "}", "finally", "{", "sendKeyLoadCompleted", "(", "clusterSize", ",", "loadError", ")", ";", "if", "(", "keys", "instanceof", "Closeable", ")", "{", "closeResource", "(", "(", "Closeable", ")", "keys", ")", ";", "}", "}", "}" ]
Loads keys from the map loader and sends them to the partition owners in batches for value loading. This method will return after all keys have been dispatched to the partition owners for value loading and all partitions have been notified that the key loading has completed. The values will still be loaded asynchronously and can be put into the record stores after this method has returned. If there is a configured max size policy per node, the keys will be loaded until this many keys have been loaded from the map loader. If the keys returned from the map loader are not equally distributed over all partitions, this may cause some nodes to load more entries than others and exceed the configured policy. @param mapStoreContext the map store context for this map @param replaceExistingValues if the existing entries for the loaded keys should be replaced @throws Exception if there was an exception when notifying the record stores that the key loading has finished @see MapLoader#loadAllKeys()
[ "Loads", "keys", "from", "the", "map", "loader", "and", "sends", "them", "to", "the", "partition", "owners", "in", "batches", "for", "value", "loading", ".", "This", "method", "will", "return", "after", "all", "keys", "have", "been", "dispatched", "to", "the", "partition", "owners", "for", "value", "loading", "and", "all", "partitions", "have", "been", "notified", "that", "the", "key", "loading", "has", "completed", ".", "The", "values", "will", "still", "be", "loaded", "asynchronously", "and", "can", "be", "put", "into", "the", "record", "stores", "after", "this", "method", "has", "returned", ".", "If", "there", "is", "a", "configured", "max", "size", "policy", "per", "node", "the", "keys", "will", "be", "loaded", "until", "this", "many", "keys", "have", "been", "loaded", "from", "the", "map", "loader", ".", "If", "the", "keys", "returned", "from", "the", "map", "loader", "are", "not", "equally", "distributed", "over", "all", "partitions", "this", "may", "cause", "some", "nodes", "to", "load", "more", "entries", "than", "others", "and", "exceed", "the", "configured", "policy", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L413-L457
15,504
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.sendBatch
private List<Future> sendBatch(Map<Integer, List<Data>> batch, boolean replaceExistingValues) { Set<Entry<Integer, List<Data>>> entries = batch.entrySet(); List<Future> futures = new ArrayList<>(entries.size()); for (Entry<Integer, List<Data>> e : entries) { int partitionId = e.getKey(); List<Data> keys = e.getValue(); MapOperation op = operationProvider.createLoadAllOperation(mapName, keys, replaceExistingValues); InternalCompletableFuture<Object> future = opService.invokeOnPartition(SERVICE_NAME, op, partitionId); futures.add(future); } return futures; }
java
private List<Future> sendBatch(Map<Integer, List<Data>> batch, boolean replaceExistingValues) { Set<Entry<Integer, List<Data>>> entries = batch.entrySet(); List<Future> futures = new ArrayList<>(entries.size()); for (Entry<Integer, List<Data>> e : entries) { int partitionId = e.getKey(); List<Data> keys = e.getValue(); MapOperation op = operationProvider.createLoadAllOperation(mapName, keys, replaceExistingValues); InternalCompletableFuture<Object> future = opService.invokeOnPartition(SERVICE_NAME, op, partitionId); futures.add(future); } return futures; }
[ "private", "List", "<", "Future", ">", "sendBatch", "(", "Map", "<", "Integer", ",", "List", "<", "Data", ">", ">", "batch", ",", "boolean", "replaceExistingValues", ")", "{", "Set", "<", "Entry", "<", "Integer", ",", "List", "<", "Data", ">", ">", ">", "entries", "=", "batch", ".", "entrySet", "(", ")", ";", "List", "<", "Future", ">", "futures", "=", "new", "ArrayList", "<>", "(", "entries", ".", "size", "(", ")", ")", ";", "for", "(", "Entry", "<", "Integer", ",", "List", "<", "Data", ">", ">", "e", ":", "entries", ")", "{", "int", "partitionId", "=", "e", ".", "getKey", "(", ")", ";", "List", "<", "Data", ">", "keys", "=", "e", ".", "getValue", "(", ")", ";", "MapOperation", "op", "=", "operationProvider", ".", "createLoadAllOperation", "(", "mapName", ",", "keys", ",", "replaceExistingValues", ")", ";", "InternalCompletableFuture", "<", "Object", ">", "future", "=", "opService", ".", "invokeOnPartition", "(", "SERVICE_NAME", ",", "op", ",", "partitionId", ")", ";", "futures", ".", "add", "(", "future", ")", ";", "}", "return", "futures", ";", "}" ]
Sends the key batches to the partition owners for value loading. The returned futures represent pending offloading of the value loading on the partition owner. This means that once the partition owner receives the keys, it will offload the value loading task and return immediately, thus completing the future. The future does not mean the value loading tasks have been completed or that the entries have been loaded and put into the record store. @param batch a map from partition ID to a batch of keys for that partition @param replaceExistingValues if the existing entries for the loaded keys should be replaced @return a list of futures representing pending completion of the value offloading task
[ "Sends", "the", "key", "batches", "to", "the", "partition", "owners", "for", "value", "loading", ".", "The", "returned", "futures", "represent", "pending", "offloading", "of", "the", "value", "loading", "on", "the", "partition", "owner", ".", "This", "means", "that", "once", "the", "partition", "owner", "receives", "the", "keys", "it", "will", "offload", "the", "value", "loading", "task", "and", "return", "immediately", "thus", "completing", "the", "future", ".", "The", "future", "does", "not", "mean", "the", "value", "loading", "tasks", "have", "been", "completed", "or", "that", "the", "entries", "have", "been", "loaded", "and", "put", "into", "the", "record", "store", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L471-L484
15,505
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/operationparker/impl/WaitSet.java
WaitSet.unpark
public void unpark(Notifier notifier, WaitNotifyKey key) { WaitSetEntry entry = queue.peek(); while (entry != null) { Operation op = entry.getOperation(); if (notifier == op) { throw new IllegalStateException("Found cyclic wait-notify! -> " + notifier); } if (entry.isValid()) { if (entry.isExpired()) { // expired entry.onExpire(); } else if (entry.isCancelled()) { entry.onCancel(); } else { if (entry.shouldWait()) { return; } OperationService operationService = nodeEngine.getOperationService(); operationService.run(op); } entry.setValid(false); } // consume queue.poll(); entry = queue.peek(); // If parkQueue.peek() returns null, we should deregister this specific // key to avoid memory leak. By contract we know that park() and unpark() // cannot be called in parallel. // We can safely remove this queue from registration map here. if (entry == null) { waitSetMap.remove(key); } } }
java
public void unpark(Notifier notifier, WaitNotifyKey key) { WaitSetEntry entry = queue.peek(); while (entry != null) { Operation op = entry.getOperation(); if (notifier == op) { throw new IllegalStateException("Found cyclic wait-notify! -> " + notifier); } if (entry.isValid()) { if (entry.isExpired()) { // expired entry.onExpire(); } else if (entry.isCancelled()) { entry.onCancel(); } else { if (entry.shouldWait()) { return; } OperationService operationService = nodeEngine.getOperationService(); operationService.run(op); } entry.setValid(false); } // consume queue.poll(); entry = queue.peek(); // If parkQueue.peek() returns null, we should deregister this specific // key to avoid memory leak. By contract we know that park() and unpark() // cannot be called in parallel. // We can safely remove this queue from registration map here. if (entry == null) { waitSetMap.remove(key); } } }
[ "public", "void", "unpark", "(", "Notifier", "notifier", ",", "WaitNotifyKey", "key", ")", "{", "WaitSetEntry", "entry", "=", "queue", ".", "peek", "(", ")", ";", "while", "(", "entry", "!=", "null", ")", "{", "Operation", "op", "=", "entry", ".", "getOperation", "(", ")", ";", "if", "(", "notifier", "==", "op", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Found cyclic wait-notify! -> \"", "+", "notifier", ")", ";", "}", "if", "(", "entry", ".", "isValid", "(", ")", ")", "{", "if", "(", "entry", ".", "isExpired", "(", ")", ")", "{", "// expired", "entry", ".", "onExpire", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "isCancelled", "(", ")", ")", "{", "entry", ".", "onCancel", "(", ")", ";", "}", "else", "{", "if", "(", "entry", ".", "shouldWait", "(", ")", ")", "{", "return", ";", "}", "OperationService", "operationService", "=", "nodeEngine", ".", "getOperationService", "(", ")", ";", "operationService", ".", "run", "(", "op", ")", ";", "}", "entry", ".", "setValid", "(", "false", ")", ";", "}", "// consume", "queue", ".", "poll", "(", ")", ";", "entry", "=", "queue", ".", "peek", "(", ")", ";", "// If parkQueue.peek() returns null, we should deregister this specific", "// key to avoid memory leak. By contract we know that park() and unpark()", "// cannot be called in parallel.", "// We can safely remove this queue from registration map here.", "if", "(", "entry", "==", "null", ")", "{", "waitSetMap", ".", "remove", "(", "key", ")", ";", "}", "}", "}" ]
executed with an unpark for the same key.
[ "executed", "with", "an", "unpark", "for", "the", "same", "key", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/operationparker/impl/WaitSet.java#L88-L123
15,506
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/event/DefaultEntryEventFilteringStrategy.java
DefaultEntryEventFilteringStrategy.doFilter
@SuppressWarnings("checkstyle:npathcomplexity") @Override public int doFilter(EventFilter filter, Data dataKey, Object oldValue, Object dataValue, EntryEventType eventType, String mapNameOrNull) { if (filter instanceof MapPartitionLostEventFilter) { return FILTER_DOES_NOT_MATCH; } // the order of the following ifs is important! // QueryEventFilter is instance of EntryEventFilter if (filter instanceof EventListenerFilter) { if (!filter.eval(eventType.getType())) { return FILTER_DOES_NOT_MATCH; } else { filter = ((EventListenerFilter) filter).getEventFilter(); } } if (filter instanceof TrueEventFilter) { return eventType.getType(); } if (filter instanceof QueryEventFilter) { return processQueryEventFilter(filter, eventType, dataKey, oldValue, dataValue, mapNameOrNull) ? eventType.getType() : FILTER_DOES_NOT_MATCH; } if (filter instanceof EntryEventFilter) { return processEntryEventFilter(filter, dataKey) ? eventType.getType() : FILTER_DOES_NOT_MATCH; } throw new IllegalArgumentException("Unknown EventFilter type = [" + filter.getClass().getCanonicalName() + "]"); }
java
@SuppressWarnings("checkstyle:npathcomplexity") @Override public int doFilter(EventFilter filter, Data dataKey, Object oldValue, Object dataValue, EntryEventType eventType, String mapNameOrNull) { if (filter instanceof MapPartitionLostEventFilter) { return FILTER_DOES_NOT_MATCH; } // the order of the following ifs is important! // QueryEventFilter is instance of EntryEventFilter if (filter instanceof EventListenerFilter) { if (!filter.eval(eventType.getType())) { return FILTER_DOES_NOT_MATCH; } else { filter = ((EventListenerFilter) filter).getEventFilter(); } } if (filter instanceof TrueEventFilter) { return eventType.getType(); } if (filter instanceof QueryEventFilter) { return processQueryEventFilter(filter, eventType, dataKey, oldValue, dataValue, mapNameOrNull) ? eventType.getType() : FILTER_DOES_NOT_MATCH; } if (filter instanceof EntryEventFilter) { return processEntryEventFilter(filter, dataKey) ? eventType.getType() : FILTER_DOES_NOT_MATCH; } throw new IllegalArgumentException("Unknown EventFilter type = [" + filter.getClass().getCanonicalName() + "]"); }
[ "@", "SuppressWarnings", "(", "\"checkstyle:npathcomplexity\"", ")", "@", "Override", "public", "int", "doFilter", "(", "EventFilter", "filter", ",", "Data", "dataKey", ",", "Object", "oldValue", ",", "Object", "dataValue", ",", "EntryEventType", "eventType", ",", "String", "mapNameOrNull", ")", "{", "if", "(", "filter", "instanceof", "MapPartitionLostEventFilter", ")", "{", "return", "FILTER_DOES_NOT_MATCH", ";", "}", "// the order of the following ifs is important!", "// QueryEventFilter is instance of EntryEventFilter", "if", "(", "filter", "instanceof", "EventListenerFilter", ")", "{", "if", "(", "!", "filter", ".", "eval", "(", "eventType", ".", "getType", "(", ")", ")", ")", "{", "return", "FILTER_DOES_NOT_MATCH", ";", "}", "else", "{", "filter", "=", "(", "(", "EventListenerFilter", ")", "filter", ")", ".", "getEventFilter", "(", ")", ";", "}", "}", "if", "(", "filter", "instanceof", "TrueEventFilter", ")", "{", "return", "eventType", ".", "getType", "(", ")", ";", "}", "if", "(", "filter", "instanceof", "QueryEventFilter", ")", "{", "return", "processQueryEventFilter", "(", "filter", ",", "eventType", ",", "dataKey", ",", "oldValue", ",", "dataValue", ",", "mapNameOrNull", ")", "?", "eventType", ".", "getType", "(", ")", ":", "FILTER_DOES_NOT_MATCH", ";", "}", "if", "(", "filter", "instanceof", "EntryEventFilter", ")", "{", "return", "processEntryEventFilter", "(", "filter", ",", "dataKey", ")", "?", "eventType", ".", "getType", "(", ")", ":", "FILTER_DOES_NOT_MATCH", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Unknown EventFilter type = [\"", "+", "filter", ".", "getClass", "(", ")", ".", "getCanonicalName", "(", ")", "+", "\"]\"", ")", ";", "}" ]
provides the default backwards compatible filtering strategy implementation.
[ "provides", "the", "default", "backwards", "compatible", "filtering", "strategy", "implementation", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/event/DefaultEntryEventFilteringStrategy.java#L64-L92
15,507
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/event/QueryCacheEventPublisher.java
QueryCacheEventPublisher.getCQCEventTypeOrNull
private EntryEventType getCQCEventTypeOrNull(EntryEventType eventType, EventFilter eventFilter, Data dataKey, Data dataNewValue, Data dataOldValue, String mapName) { boolean newValueMatching = filteringStrategy.doFilter(eventFilter, dataKey, dataOldValue, dataNewValue, eventType, mapName) != FilteringStrategy.FILTER_DOES_NOT_MATCH; if (eventType == UPDATED) { // UPDATED event has a special handling as it might result in either ADDING or REMOVING an entry to/from CQC // depending on a predicate boolean oldValueMatching = filteringStrategy.doFilter(eventFilter, dataKey, null, dataOldValue, EntryEventType.ADDED, mapName) != FilteringStrategy.FILTER_DOES_NOT_MATCH; if (oldValueMatching) { if (!newValueMatching) { eventType = REMOVED; } } else { if (newValueMatching) { eventType = ADDED; } else { //neither old value nor new value is matching -> it's a non-event for the CQC return null; } } } else if (!newValueMatching) { return null; } return eventType; }
java
private EntryEventType getCQCEventTypeOrNull(EntryEventType eventType, EventFilter eventFilter, Data dataKey, Data dataNewValue, Data dataOldValue, String mapName) { boolean newValueMatching = filteringStrategy.doFilter(eventFilter, dataKey, dataOldValue, dataNewValue, eventType, mapName) != FilteringStrategy.FILTER_DOES_NOT_MATCH; if (eventType == UPDATED) { // UPDATED event has a special handling as it might result in either ADDING or REMOVING an entry to/from CQC // depending on a predicate boolean oldValueMatching = filteringStrategy.doFilter(eventFilter, dataKey, null, dataOldValue, EntryEventType.ADDED, mapName) != FilteringStrategy.FILTER_DOES_NOT_MATCH; if (oldValueMatching) { if (!newValueMatching) { eventType = REMOVED; } } else { if (newValueMatching) { eventType = ADDED; } else { //neither old value nor new value is matching -> it's a non-event for the CQC return null; } } } else if (!newValueMatching) { return null; } return eventType; }
[ "private", "EntryEventType", "getCQCEventTypeOrNull", "(", "EntryEventType", "eventType", ",", "EventFilter", "eventFilter", ",", "Data", "dataKey", ",", "Data", "dataNewValue", ",", "Data", "dataOldValue", ",", "String", "mapName", ")", "{", "boolean", "newValueMatching", "=", "filteringStrategy", ".", "doFilter", "(", "eventFilter", ",", "dataKey", ",", "dataOldValue", ",", "dataNewValue", ",", "eventType", ",", "mapName", ")", "!=", "FilteringStrategy", ".", "FILTER_DOES_NOT_MATCH", ";", "if", "(", "eventType", "==", "UPDATED", ")", "{", "// UPDATED event has a special handling as it might result in either ADDING or REMOVING an entry to/from CQC", "// depending on a predicate", "boolean", "oldValueMatching", "=", "filteringStrategy", ".", "doFilter", "(", "eventFilter", ",", "dataKey", ",", "null", ",", "dataOldValue", ",", "EntryEventType", ".", "ADDED", ",", "mapName", ")", "!=", "FilteringStrategy", ".", "FILTER_DOES_NOT_MATCH", ";", "if", "(", "oldValueMatching", ")", "{", "if", "(", "!", "newValueMatching", ")", "{", "eventType", "=", "REMOVED", ";", "}", "}", "else", "{", "if", "(", "newValueMatching", ")", "{", "eventType", "=", "ADDED", ";", "}", "else", "{", "//neither old value nor new value is matching -> it's a non-event for the CQC", "return", "null", ";", "}", "}", "}", "else", "if", "(", "!", "newValueMatching", ")", "{", "return", "null", ";", "}", "return", "eventType", ";", "}" ]
other filtering strategy is in place
[ "other", "filtering", "strategy", "is", "in", "place" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/event/QueryCacheEventPublisher.java#L157-L182
15,508
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/executor/StripedExecutor.java
StripedExecutor.getWorkQueueSize
public int getWorkQueueSize() { int size = 0; for (Worker worker : workers) { size += worker.taskQueue.size(); } return size; }
java
public int getWorkQueueSize() { int size = 0; for (Worker worker : workers) { size += worker.taskQueue.size(); } return size; }
[ "public", "int", "getWorkQueueSize", "(", ")", "{", "int", "size", "=", "0", ";", "for", "(", "Worker", "worker", ":", "workers", ")", "{", "size", "+=", "worker", ".", "taskQueue", ".", "size", "(", ")", ";", "}", "return", "size", ";", "}" ]
Returns the total number of tasks pending to be executed. @return total work queue size.
[ "Returns", "the", "total", "number", "of", "tasks", "pending", "to", "be", "executed", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/executor/StripedExecutor.java#L98-L104
15,509
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/executor/StripedExecutor.java
StripedExecutor.processedCount
public long processedCount() { long size = 0; for (Worker worker : workers) { size += worker.processed.inc(); } return size; }
java
public long processedCount() { long size = 0; for (Worker worker : workers) { size += worker.processed.inc(); } return size; }
[ "public", "long", "processedCount", "(", ")", "{", "long", "size", "=", "0", ";", "for", "(", "Worker", "worker", ":", "workers", ")", "{", "size", "+=", "worker", ".", "processed", ".", "inc", "(", ")", ";", "}", "return", "size", ";", "}" ]
Returns the total number of processed events.
[ "Returns", "the", "total", "number", "of", "processed", "events", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/executor/StripedExecutor.java#L109-L115
15,510
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/OperationBackupHandler.java
OperationBackupHandler.sendBackups
int sendBackups(Operation op) throws Exception { if (!(op instanceof BackupAwareOperation)) { return 0; } int backupAcks = 0; BackupAwareOperation backupAwareOp = (BackupAwareOperation) op; if (backupAwareOp.shouldBackup()) { backupAcks = sendBackups0(backupAwareOp); } return backupAcks; }
java
int sendBackups(Operation op) throws Exception { if (!(op instanceof BackupAwareOperation)) { return 0; } int backupAcks = 0; BackupAwareOperation backupAwareOp = (BackupAwareOperation) op; if (backupAwareOp.shouldBackup()) { backupAcks = sendBackups0(backupAwareOp); } return backupAcks; }
[ "int", "sendBackups", "(", "Operation", "op", ")", "throws", "Exception", "{", "if", "(", "!", "(", "op", "instanceof", "BackupAwareOperation", ")", ")", "{", "return", "0", ";", "}", "int", "backupAcks", "=", "0", ";", "BackupAwareOperation", "backupAwareOp", "=", "(", "BackupAwareOperation", ")", "op", ";", "if", "(", "backupAwareOp", ".", "shouldBackup", "(", ")", ")", "{", "backupAcks", "=", "sendBackups0", "(", "backupAwareOp", ")", ";", "}", "return", "backupAcks", ";", "}" ]
Sends the appropriate backups. This call will not wait till the backups have ACK'ed. If this call is made with a none BackupAwareOperation, then 0 is returned. @param op the Operation to backup. @return the number of ACKS required to complete the invocation. @throws Exception if there is any exception sending the backups.
[ "Sends", "the", "appropriate", "backups", ".", "This", "call", "will", "not", "wait", "till", "the", "backups", "have", "ACK", "ed", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/OperationBackupHandler.java#L71-L82
15,511
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/AddressUtil.java
AddressUtil.getAddressMatcher
public static AddressMatcher getAddressMatcher(String address) { final AddressMatcher matcher; final int indexColon = address.indexOf(':'); final int lastIndexColon = address.lastIndexOf(':'); final int indexDot = address.indexOf('.'); final int lastIndexDot = address.lastIndexOf('.'); if (indexColon > -1 && lastIndexColon > indexColon) { if (indexDot == -1) { matcher = new Ip6AddressMatcher(); parseIpv6(matcher, address); } else { // IPv4 mapped IPv6 if (indexDot >= lastIndexDot) { throw new InvalidAddressException(address); } final int lastIndexColon2 = address.lastIndexOf(':'); final String host2 = address.substring(lastIndexColon2 + 1); matcher = new Ip4AddressMatcher(); parseIpv4(matcher, host2); } } else if (indexDot > -1 && lastIndexDot > indexDot && indexColon == -1) { // IPv4 matcher = new Ip4AddressMatcher(); parseIpv4(matcher, address); } else { throw new InvalidAddressException(address); } return matcher; }
java
public static AddressMatcher getAddressMatcher(String address) { final AddressMatcher matcher; final int indexColon = address.indexOf(':'); final int lastIndexColon = address.lastIndexOf(':'); final int indexDot = address.indexOf('.'); final int lastIndexDot = address.lastIndexOf('.'); if (indexColon > -1 && lastIndexColon > indexColon) { if (indexDot == -1) { matcher = new Ip6AddressMatcher(); parseIpv6(matcher, address); } else { // IPv4 mapped IPv6 if (indexDot >= lastIndexDot) { throw new InvalidAddressException(address); } final int lastIndexColon2 = address.lastIndexOf(':'); final String host2 = address.substring(lastIndexColon2 + 1); matcher = new Ip4AddressMatcher(); parseIpv4(matcher, host2); } } else if (indexDot > -1 && lastIndexDot > indexDot && indexColon == -1) { // IPv4 matcher = new Ip4AddressMatcher(); parseIpv4(matcher, address); } else { throw new InvalidAddressException(address); } return matcher; }
[ "public", "static", "AddressMatcher", "getAddressMatcher", "(", "String", "address", ")", "{", "final", "AddressMatcher", "matcher", ";", "final", "int", "indexColon", "=", "address", ".", "indexOf", "(", "'", "'", ")", ";", "final", "int", "lastIndexColon", "=", "address", ".", "lastIndexOf", "(", "'", "'", ")", ";", "final", "int", "indexDot", "=", "address", ".", "indexOf", "(", "'", "'", ")", ";", "final", "int", "lastIndexDot", "=", "address", ".", "lastIndexOf", "(", "'", "'", ")", ";", "if", "(", "indexColon", ">", "-", "1", "&&", "lastIndexColon", ">", "indexColon", ")", "{", "if", "(", "indexDot", "==", "-", "1", ")", "{", "matcher", "=", "new", "Ip6AddressMatcher", "(", ")", ";", "parseIpv6", "(", "matcher", ",", "address", ")", ";", "}", "else", "{", "// IPv4 mapped IPv6", "if", "(", "indexDot", ">=", "lastIndexDot", ")", "{", "throw", "new", "InvalidAddressException", "(", "address", ")", ";", "}", "final", "int", "lastIndexColon2", "=", "address", ".", "lastIndexOf", "(", "'", "'", ")", ";", "final", "String", "host2", "=", "address", ".", "substring", "(", "lastIndexColon2", "+", "1", ")", ";", "matcher", "=", "new", "Ip4AddressMatcher", "(", ")", ";", "parseIpv4", "(", "matcher", ",", "host2", ")", ";", "}", "}", "else", "if", "(", "indexDot", ">", "-", "1", "&&", "lastIndexDot", ">", "indexDot", "&&", "indexColon", "==", "-", "1", ")", "{", "// IPv4", "matcher", "=", "new", "Ip4AddressMatcher", "(", ")", ";", "parseIpv4", "(", "matcher", ",", "address", ")", ";", "}", "else", "{", "throw", "new", "InvalidAddressException", "(", "address", ")", ";", "}", "return", "matcher", ";", "}" ]
Gets an AddressMatcher for a given addresses. @param address the address @return the returned AddressMatcher. The returned value will never be null. @throws com.hazelcast.util.AddressUtil.InvalidAddressException if the address is not valid.
[ "Gets", "an", "AddressMatcher", "for", "a", "given", "addresses", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/AddressUtil.java#L308-L337
15,512
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/merge/AbstractContainerMerger.java
AbstractContainerMerger.invoke
protected void invoke(String serviceName, Operation operation, int partitionId) { try { operationCount++; operationService .invokeOnPartition(serviceName, operation, partitionId) .andThen(mergeCallback); } catch (Throwable t) { throw rethrow(t); } }
java
protected void invoke(String serviceName, Operation operation, int partitionId) { try { operationCount++; operationService .invokeOnPartition(serviceName, operation, partitionId) .andThen(mergeCallback); } catch (Throwable t) { throw rethrow(t); } }
[ "protected", "void", "invoke", "(", "String", "serviceName", ",", "Operation", "operation", ",", "int", "partitionId", ")", "{", "try", "{", "operationCount", "++", ";", "operationService", ".", "invokeOnPartition", "(", "serviceName", ",", "operation", ",", "partitionId", ")", ".", "andThen", "(", "mergeCallback", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "rethrow", "(", "t", ")", ";", "}", "}" ]
Invokes the given merge operation. @param serviceName the service name @param operation the merge operation @param partitionId the partition ID of the operation
[ "Invokes", "the", "given", "merge", "operation", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/merge/AbstractContainerMerger.java#L127-L136
15,513
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/cache/impl/operation/CacheOperation.java
CacheOperation.rethrowOrSwallowIfBackup
private void rethrowOrSwallowIfBackup(CacheNotExistsException e) throws Exception { if (this instanceof BackupOperation) { getLogger().finest("Error while getting a cache", e); } else { throw ExceptionUtil.rethrow(e, Exception.class); } }
java
private void rethrowOrSwallowIfBackup(CacheNotExistsException e) throws Exception { if (this instanceof BackupOperation) { getLogger().finest("Error while getting a cache", e); } else { throw ExceptionUtil.rethrow(e, Exception.class); } }
[ "private", "void", "rethrowOrSwallowIfBackup", "(", "CacheNotExistsException", "e", ")", "throws", "Exception", "{", "if", "(", "this", "instanceof", "BackupOperation", ")", "{", "getLogger", "(", ")", ".", "finest", "(", "\"Error while getting a cache\"", ",", "e", ")", ";", "}", "else", "{", "throw", "ExceptionUtil", ".", "rethrow", "(", "e", ",", "Exception", ".", "class", ")", ";", "}", "}" ]
If a backup operation wants to get a deleted cache, swallows exception by only logging it. If it is not a backup operation, just rethrows exception.
[ "If", "a", "backup", "operation", "wants", "to", "get", "a", "deleted", "cache", "swallows", "exception", "by", "only", "logging", "it", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cache/impl/operation/CacheOperation.java#L119-L125
15,514
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/operationparker/impl/OperationParkerImpl.java
OperationParkerImpl.onMemberLeft
public void onMemberLeft(MemberImpl leftMember) { for (WaitSet waitSet : waitSetMap.values()) { waitSet.invalidateAll(leftMember.getUuid()); } }
java
public void onMemberLeft(MemberImpl leftMember) { for (WaitSet waitSet : waitSetMap.values()) { waitSet.invalidateAll(leftMember.getUuid()); } }
[ "public", "void", "onMemberLeft", "(", "MemberImpl", "leftMember", ")", "{", "for", "(", "WaitSet", "waitSet", ":", "waitSetMap", ".", "values", "(", ")", ")", "{", "waitSet", ".", "invalidateAll", "(", "leftMember", ".", "getUuid", "(", ")", ")", ";", "}", "}" ]
invalidated waiting ops will removed from queue eventually by notifiers.
[ "invalidated", "waiting", "ops", "will", "removed", "from", "queue", "eventually", "by", "notifiers", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/operationparker/impl/OperationParkerImpl.java#L134-L138
15,515
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterServiceImpl.java
ClusterServiceImpl.shouldAcceptMastership
private boolean shouldAcceptMastership(MemberMap memberMap, MemberImpl candidate) { assert lock.isHeldByCurrentThread() : "Called without holding cluster service lock!"; for (MemberImpl member : memberMap.headMemberSet(candidate, false)) { if (!membershipManager.isMemberSuspected(member.getAddress())) { if (logger.isFineEnabled()) { logger.fine("Should not accept mastership claim of " + candidate + ", because " + member + " is not suspected at the moment and is before than " + candidate + " in the member list."); } return false; } } return true; }
java
private boolean shouldAcceptMastership(MemberMap memberMap, MemberImpl candidate) { assert lock.isHeldByCurrentThread() : "Called without holding cluster service lock!"; for (MemberImpl member : memberMap.headMemberSet(candidate, false)) { if (!membershipManager.isMemberSuspected(member.getAddress())) { if (logger.isFineEnabled()) { logger.fine("Should not accept mastership claim of " + candidate + ", because " + member + " is not suspected at the moment and is before than " + candidate + " in the member list."); } return false; } } return true; }
[ "private", "boolean", "shouldAcceptMastership", "(", "MemberMap", "memberMap", ",", "MemberImpl", "candidate", ")", "{", "assert", "lock", ".", "isHeldByCurrentThread", "(", ")", ":", "\"Called without holding cluster service lock!\"", ";", "for", "(", "MemberImpl", "member", ":", "memberMap", ".", "headMemberSet", "(", "candidate", ",", "false", ")", ")", "{", "if", "(", "!", "membershipManager", ".", "isMemberSuspected", "(", "member", ".", "getAddress", "(", ")", ")", ")", "{", "if", "(", "logger", ".", "isFineEnabled", "(", ")", ")", "{", "logger", ".", "fine", "(", "\"Should not accept mastership claim of \"", "+", "candidate", "+", "\", because \"", "+", "member", "+", "\" is not suspected at the moment and is before than \"", "+", "candidate", "+", "\" in the member list.\"", ")", ";", "}", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
mastership is accepted when all members before the candidate is suspected
[ "mastership", "is", "accepted", "when", "all", "members", "before", "the", "candidate", "is", "suspected" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterServiceImpl.java#L285-L298
15,516
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterServiceImpl.java
ClusterServiceImpl.setMasterAddress
void setMasterAddress(Address master) { assert lock.isHeldByCurrentThread() : "Called without holding cluster service lock!"; if (logger.isFineEnabled()) { logger.fine("Setting master address to " + master); } masterAddress = master; }
java
void setMasterAddress(Address master) { assert lock.isHeldByCurrentThread() : "Called without holding cluster service lock!"; if (logger.isFineEnabled()) { logger.fine("Setting master address to " + master); } masterAddress = master; }
[ "void", "setMasterAddress", "(", "Address", "master", ")", "{", "assert", "lock", ".", "isHeldByCurrentThread", "(", ")", ":", "\"Called without holding cluster service lock!\"", ";", "if", "(", "logger", ".", "isFineEnabled", "(", ")", ")", "{", "logger", ".", "fine", "(", "\"Setting master address to \"", "+", "master", ")", ";", "}", "masterAddress", "=", "master", ";", "}" ]
should be called under lock
[ "should", "be", "called", "under", "lock" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterServiceImpl.java#L658-L664
15,517
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/nio/tcp/BindHandler.java
BindHandler.bind
private synchronized void bind(TcpIpConnection connection, Address remoteEndPoint, Address localEndpoint, boolean reply) { if (logger.isFinestEnabled()) { logger.finest("Binding " + connection + " to " + remoteEndPoint + ", reply is " + reply); } final Address thisAddress = ioService.getThisAddress(); // Some simple spoofing attack prevention // Prevent BINDs from src that doesn't match the BIND local address // Prevent BINDs from src that match us (same host & port) if (spoofingChecks && (!ensureValidBindSource(connection, remoteEndPoint) || !ensureBindNotFromSelf(connection, remoteEndPoint, thisAddress))) { return; } // Prevent BINDs that don't have this node as the destination if (!ensureValidBindTarget(connection, remoteEndPoint, localEndpoint, thisAddress)) { return; } bind0(connection, remoteEndPoint, null, reply); }
java
private synchronized void bind(TcpIpConnection connection, Address remoteEndPoint, Address localEndpoint, boolean reply) { if (logger.isFinestEnabled()) { logger.finest("Binding " + connection + " to " + remoteEndPoint + ", reply is " + reply); } final Address thisAddress = ioService.getThisAddress(); // Some simple spoofing attack prevention // Prevent BINDs from src that doesn't match the BIND local address // Prevent BINDs from src that match us (same host & port) if (spoofingChecks && (!ensureValidBindSource(connection, remoteEndPoint) || !ensureBindNotFromSelf(connection, remoteEndPoint, thisAddress))) { return; } // Prevent BINDs that don't have this node as the destination if (!ensureValidBindTarget(connection, remoteEndPoint, localEndpoint, thisAddress)) { return; } bind0(connection, remoteEndPoint, null, reply); }
[ "private", "synchronized", "void", "bind", "(", "TcpIpConnection", "connection", ",", "Address", "remoteEndPoint", ",", "Address", "localEndpoint", ",", "boolean", "reply", ")", "{", "if", "(", "logger", ".", "isFinestEnabled", "(", ")", ")", "{", "logger", ".", "finest", "(", "\"Binding \"", "+", "connection", "+", "\" to \"", "+", "remoteEndPoint", "+", "\", reply is \"", "+", "reply", ")", ";", "}", "final", "Address", "thisAddress", "=", "ioService", ".", "getThisAddress", "(", ")", ";", "// Some simple spoofing attack prevention", "// Prevent BINDs from src that doesn't match the BIND local address", "// Prevent BINDs from src that match us (same host & port)", "if", "(", "spoofingChecks", "&&", "(", "!", "ensureValidBindSource", "(", "connection", ",", "remoteEndPoint", ")", "||", "!", "ensureBindNotFromSelf", "(", "connection", ",", "remoteEndPoint", ",", "thisAddress", ")", ")", ")", "{", "return", ";", "}", "// Prevent BINDs that don't have this node as the destination", "if", "(", "!", "ensureValidBindTarget", "(", "connection", ",", "remoteEndPoint", ",", "localEndpoint", ",", "thisAddress", ")", ")", "{", "return", ";", "}", "bind0", "(", "connection", ",", "remoteEndPoint", ",", "null", ",", "reply", ")", ";", "}" ]
Binding completes the connection and makes it available to be used with the ConnectionManager.
[ "Binding", "completes", "the", "connection", "and", "makes", "it", "available", "to", "be", "used", "with", "the", "ConnectionManager", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/nio/tcp/BindHandler.java#L126-L147
15,518
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/networking/OutboundHandler.java
OutboundHandler.initDstBuffer
protected final void initDstBuffer(int sizeBytes, byte[] bytes) { if (bytes != null && bytes.length > sizeBytes) { throw new IllegalArgumentException("Buffer overflow. Can't initialize dstBuffer for " + this + " and channel" + channel + " because too many bytes, sizeBytes " + sizeBytes + ". bytes.length " + bytes.length); } ChannelOptions config = channel.options(); ByteBuffer buffer = newByteBuffer(sizeBytes, config.getOption(DIRECT_BUF)); if (bytes != null) { buffer.put(bytes); } buffer.flip(); dst = (D) buffer; }
java
protected final void initDstBuffer(int sizeBytes, byte[] bytes) { if (bytes != null && bytes.length > sizeBytes) { throw new IllegalArgumentException("Buffer overflow. Can't initialize dstBuffer for " + this + " and channel" + channel + " because too many bytes, sizeBytes " + sizeBytes + ". bytes.length " + bytes.length); } ChannelOptions config = channel.options(); ByteBuffer buffer = newByteBuffer(sizeBytes, config.getOption(DIRECT_BUF)); if (bytes != null) { buffer.put(bytes); } buffer.flip(); dst = (D) buffer; }
[ "protected", "final", "void", "initDstBuffer", "(", "int", "sizeBytes", ",", "byte", "[", "]", "bytes", ")", "{", "if", "(", "bytes", "!=", "null", "&&", "bytes", ".", "length", ">", "sizeBytes", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Buffer overflow. Can't initialize dstBuffer for \"", "+", "this", "+", "\" and channel\"", "+", "channel", "+", "\" because too many bytes, sizeBytes \"", "+", "sizeBytes", "+", "\". bytes.length \"", "+", "bytes", ".", "length", ")", ";", "}", "ChannelOptions", "config", "=", "channel", ".", "options", "(", ")", ";", "ByteBuffer", "buffer", "=", "newByteBuffer", "(", "sizeBytes", ",", "config", ".", "getOption", "(", "DIRECT_BUF", ")", ")", ";", "if", "(", "bytes", "!=", "null", ")", "{", "buffer", ".", "put", "(", "bytes", ")", ";", "}", "buffer", ".", "flip", "(", ")", ";", "dst", "=", "(", "D", ")", "buffer", ";", "}" ]
Initializes the dst ByteBuffer with the configured size. The buffer created is reading mode. @param sizeBytes the size of the dst ByteBuffer. @param bytes the bytes added to the buffer. Can be null if nothing should be added. @throws IllegalArgumentException if the size of the buffer is too small.
[ "Initializes", "the", "dst", "ByteBuffer", "with", "the", "configured", "size", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/networking/OutboundHandler.java#L108-L122
15,519
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/InvocationBuilder.java
InvocationBuilder.setReplicaIndex
public InvocationBuilder setReplicaIndex(int replicaIndex) { if (replicaIndex < 0 || replicaIndex >= InternalPartition.MAX_REPLICA_COUNT) { throw new IllegalArgumentException("Replica index is out of range [0-" + (InternalPartition.MAX_REPLICA_COUNT - 1) + "]"); } this.replicaIndex = replicaIndex; return this; }
java
public InvocationBuilder setReplicaIndex(int replicaIndex) { if (replicaIndex < 0 || replicaIndex >= InternalPartition.MAX_REPLICA_COUNT) { throw new IllegalArgumentException("Replica index is out of range [0-" + (InternalPartition.MAX_REPLICA_COUNT - 1) + "]"); } this.replicaIndex = replicaIndex; return this; }
[ "public", "InvocationBuilder", "setReplicaIndex", "(", "int", "replicaIndex", ")", "{", "if", "(", "replicaIndex", "<", "0", "||", "replicaIndex", ">=", "InternalPartition", ".", "MAX_REPLICA_COUNT", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Replica index is out of range [0-\"", "+", "(", "InternalPartition", ".", "MAX_REPLICA_COUNT", "-", "1", ")", "+", "\"]\"", ")", ";", "}", "this", ".", "replicaIndex", "=", "replicaIndex", ";", "return", "this", ";", "}" ]
Sets the replicaIndex. @param replicaIndex the replica index @return the InvocationBuilder @throws java.lang.IllegalArgumentException if replicaIndex smaller than 0 or larger than the max replica count.
[ "Sets", "the", "replicaIndex", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/InvocationBuilder.java#L98-L105
15,520
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/writebehind/WriteBehindManager.java
WriteBehindManager.getMapDataStore
@Override public MapDataStore getMapDataStore(String mapName, int partitionId) { return MapDataStores.createWriteBehindStore(mapStoreContext, partitionId, writeBehindProcessor); }
java
@Override public MapDataStore getMapDataStore(String mapName, int partitionId) { return MapDataStores.createWriteBehindStore(mapStoreContext, partitionId, writeBehindProcessor); }
[ "@", "Override", "public", "MapDataStore", "getMapDataStore", "(", "String", "mapName", ",", "int", "partitionId", ")", "{", "return", "MapDataStores", ".", "createWriteBehindStore", "(", "mapStoreContext", ",", "partitionId", ",", "writeBehindProcessor", ")", ";", "}" ]
todo get this via constructor function.
[ "todo", "get", "this", "via", "constructor", "function", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/writebehind/WriteBehindManager.java#L56-L59
15,521
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.add
public int add(Callable task) { int index = findEmptySpot(); callableCounter++; ringItems[index] = task; isTask[index] = true; sequences[index] = head; return head; }
java
public int add(Callable task) { int index = findEmptySpot(); callableCounter++; ringItems[index] = task; isTask[index] = true; sequences[index] = head; return head; }
[ "public", "int", "add", "(", "Callable", "task", ")", "{", "int", "index", "=", "findEmptySpot", "(", ")", ";", "callableCounter", "++", ";", "ringItems", "[", "index", "]", "=", "task", ";", "isTask", "[", "index", "]", "=", "true", ";", "sequences", "[", "index", "]", "=", "head", ";", "return", "head", ";", "}" ]
Adds the task to next available spot and returns the sequence corresponding to that spot. throws exception if there is no available spot @param task The task @return the sequence @throws RejectedExecutionException if there is not available spot for the task
[ "Adds", "the", "task", "to", "next", "available", "spot", "and", "returns", "the", "sequence", "corresponding", "to", "that", "spot", ".", "throws", "exception", "if", "there", "is", "no", "available", "spot" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L59-L66
15,522
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.remove
public void remove(int sequence) { int index = toIndex(sequence); ringItems[index] = null; isTask[index] = false; head--; callableCounter--; }
java
public void remove(int sequence) { int index = toIndex(sequence); ringItems[index] = null; isTask[index] = false; head--; callableCounter--; }
[ "public", "void", "remove", "(", "int", "sequence", ")", "{", "int", "index", "=", "toIndex", "(", "sequence", ")", ";", "ringItems", "[", "index", "]", "=", "null", ";", "isTask", "[", "index", "]", "=", "false", ";", "head", "--", ";", "callableCounter", "--", ";", "}" ]
Removes the task with the given sequence @param sequence the sequence
[ "Removes", "the", "task", "with", "the", "given", "sequence" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L87-L93
15,523
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.putBackup
void putBackup(int sequence, Callable task) { head = Math.max(head, sequence); callableCounter++; int index = toIndex(sequence); ringItems[index] = task; isTask[index] = true; sequences[index] = sequence; }
java
void putBackup(int sequence, Callable task) { head = Math.max(head, sequence); callableCounter++; int index = toIndex(sequence); ringItems[index] = task; isTask[index] = true; sequences[index] = sequence; }
[ "void", "putBackup", "(", "int", "sequence", ",", "Callable", "task", ")", "{", "head", "=", "Math", ".", "max", "(", "head", ",", "sequence", ")", ";", "callableCounter", "++", ";", "int", "index", "=", "toIndex", "(", "sequence", ")", ";", "ringItems", "[", "index", "]", "=", "task", ";", "isTask", "[", "index", "]", "=", "true", ";", "sequences", "[", "index", "]", "=", "sequence", ";", "}" ]
Puts the task for the given sequence @param sequence The sequence @param task The task
[ "Puts", "the", "task", "for", "the", "given", "sequence" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L101-L108
15,524
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.replaceTaskWithResult
void replaceTaskWithResult(int sequence, Object response) { int index = toIndex(sequence); // If sequence is not equal then it is disposed externally if (sequences[index] != sequence) { return; } ringItems[index] = response; isTask[index] = false; callableCounter--; }
java
void replaceTaskWithResult(int sequence, Object response) { int index = toIndex(sequence); // If sequence is not equal then it is disposed externally if (sequences[index] != sequence) { return; } ringItems[index] = response; isTask[index] = false; callableCounter--; }
[ "void", "replaceTaskWithResult", "(", "int", "sequence", ",", "Object", "response", ")", "{", "int", "index", "=", "toIndex", "(", "sequence", ")", ";", "// If sequence is not equal then it is disposed externally", "if", "(", "sequences", "[", "index", "]", "!=", "sequence", ")", "{", "return", ";", "}", "ringItems", "[", "index", "]", "=", "response", ";", "isTask", "[", "index", "]", "=", "false", ";", "callableCounter", "--", ";", "}" ]
Replaces the task with its response If the sequence does not correspond to a task then the call is ignored @param sequence The sequence @param response The response
[ "Replaces", "the", "task", "with", "its", "response", "If", "the", "sequence", "does", "not", "correspond", "to", "a", "task", "then", "the", "call", "is", "ignored" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L117-L126
15,525
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.retrieveAndDispose
Object retrieveAndDispose(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); try { return ringItems[index]; } finally { ringItems[index] = null; isTask[index] = false; head--; } }
java
Object retrieveAndDispose(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); try { return ringItems[index]; } finally { ringItems[index] = null; isTask[index] = false; head--; } }
[ "Object", "retrieveAndDispose", "(", "int", "sequence", ")", "{", "int", "index", "=", "toIndex", "(", "sequence", ")", ";", "checkSequence", "(", "index", ",", "sequence", ")", ";", "try", "{", "return", "ringItems", "[", "index", "]", ";", "}", "finally", "{", "ringItems", "[", "index", "]", "=", "null", ";", "isTask", "[", "index", "]", "=", "false", ";", "head", "--", ";", "}", "}" ]
Gets the response and disposes the sequence @param sequence The sequence @return The response
[ "Gets", "the", "response", "and", "disposes", "the", "sequence" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L134-L144
15,526
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.dispose
public void dispose(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); if (isTask[index]) { callableCounter--; } ringItems[index] = null; isTask[index] = false; }
java
public void dispose(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); if (isTask[index]) { callableCounter--; } ringItems[index] = null; isTask[index] = false; }
[ "public", "void", "dispose", "(", "int", "sequence", ")", "{", "int", "index", "=", "toIndex", "(", "sequence", ")", ";", "checkSequence", "(", "index", ",", "sequence", ")", ";", "if", "(", "isTask", "[", "index", "]", ")", "{", "callableCounter", "--", ";", "}", "ringItems", "[", "index", "]", "=", "null", ";", "isTask", "[", "index", "]", "=", "false", ";", "}" ]
Disposes the sequence @param sequence The sequence
[ "Disposes", "the", "sequence" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L151-L159
15,527
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.retrieve
public Object retrieve(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); return ringItems[index]; }
java
public Object retrieve(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); return ringItems[index]; }
[ "public", "Object", "retrieve", "(", "int", "sequence", ")", "{", "int", "index", "=", "toIndex", "(", "sequence", ")", ";", "checkSequence", "(", "index", ",", "sequence", ")", ";", "return", "ringItems", "[", "index", "]", ";", "}" ]
Gets the response @param sequence The sequence @return The response
[ "Gets", "the", "response" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L167-L171
15,528
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java
TaskRingBuffer.isTask
boolean isTask(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); return isTask[index]; }
java
boolean isTask(int sequence) { int index = toIndex(sequence); checkSequence(index, sequence); return isTask[index]; }
[ "boolean", "isTask", "(", "int", "sequence", ")", "{", "int", "index", "=", "toIndex", "(", "sequence", ")", ";", "checkSequence", "(", "index", ",", "sequence", ")", ";", "return", "isTask", "[", "index", "]", ";", "}" ]
Check if the sequence corresponds to a task @param sequence The sequence @return <tt>true</tt> if the sequence corresponds to a task, <tt>false</tt> otherwise @throws StaleTaskIdException if the solt overwritten
[ "Check", "if", "the", "sequence", "corresponds", "to", "a", "task" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/durableexecutor/impl/TaskRingBuffer.java#L180-L184
15,529
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/client/impl/ClientSelectors.java
ClientSelectors.ipSelector
public static ClientSelector ipSelector(final String ipMask) { return new ClientSelector() { @Override public boolean select(Client client) { return AddressUtil.matchInterface(client.getSocketAddress().getAddress().getHostAddress(), ipMask); } @Override public String toString() { return "ClientSelector{ipMask:" + ipMask + " }"; } }; }
java
public static ClientSelector ipSelector(final String ipMask) { return new ClientSelector() { @Override public boolean select(Client client) { return AddressUtil.matchInterface(client.getSocketAddress().getAddress().getHostAddress(), ipMask); } @Override public String toString() { return "ClientSelector{ipMask:" + ipMask + " }"; } }; }
[ "public", "static", "ClientSelector", "ipSelector", "(", "final", "String", "ipMask", ")", "{", "return", "new", "ClientSelector", "(", ")", "{", "@", "Override", "public", "boolean", "select", "(", "Client", "client", ")", "{", "return", "AddressUtil", ".", "matchInterface", "(", "client", ".", "getSocketAddress", "(", ")", ".", "getAddress", "(", ")", ".", "getHostAddress", "(", ")", ",", "ipMask", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"ClientSelector{ipMask:\"", "+", "ipMask", "+", "\" }\"", ";", "}", "}", ";", "}" ]
Works with AddressUtil.mathInterface @param ipMask ip mask for the selector @return client selector according to IP
[ "Works", "with", "AddressUtil", ".", "mathInterface" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/client/impl/ClientSelectors.java#L88-L100
15,530
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/nio/ClassLoaderUtil.java
ClassLoaderUtil.tryLoadClass
public static Class<?> tryLoadClass(String className) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException e) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); return contextClassLoader.loadClass(className); } }
java
public static Class<?> tryLoadClass(String className) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException e) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); return contextClassLoader.loadClass(className); } }
[ "public", "static", "Class", "<", "?", ">", "tryLoadClass", "(", "String", "className", ")", "throws", "ClassNotFoundException", "{", "try", "{", "return", "Class", ".", "forName", "(", "className", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "ClassLoader", "contextClassLoader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "return", "contextClassLoader", ".", "loadClass", "(", "className", ")", ";", "}", "}" ]
Tries to load the given class. @param className Name of the class to load @return Loaded class @throws ClassNotFoundException when the class is not found
[ "Tries", "to", "load", "the", "given", "class", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/nio/ClassLoaderUtil.java#L313-L320
15,531
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/nio/ClassLoaderUtil.java
ClassLoaderUtil.implementsInterfaceWithSameName
public static boolean implementsInterfaceWithSameName(Class<?> clazz, Class<?> iface) { Class<?>[] interfaces = getAllInterfaces(clazz); for (Class implementedInterface : interfaces) { if (implementedInterface.getName().equals(iface.getName())) { return true; } } return false; }
java
public static boolean implementsInterfaceWithSameName(Class<?> clazz, Class<?> iface) { Class<?>[] interfaces = getAllInterfaces(clazz); for (Class implementedInterface : interfaces) { if (implementedInterface.getName().equals(iface.getName())) { return true; } } return false; }
[ "public", "static", "boolean", "implementsInterfaceWithSameName", "(", "Class", "<", "?", ">", "clazz", ",", "Class", "<", "?", ">", "iface", ")", "{", "Class", "<", "?", ">", "[", "]", "interfaces", "=", "getAllInterfaces", "(", "clazz", ")", ";", "for", "(", "Class", "implementedInterface", ":", "interfaces", ")", "{", "if", "(", "implementedInterface", ".", "getName", "(", ")", ".", "equals", "(", "iface", ".", "getName", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check whether given class implements an interface with the same name. It returns true even when the implemented interface is loaded by a different classloader and hence the class is not assignable into it. An interface is considered as implemented when either: <ul> <li>The class directly implements the interface</li> <li>The class implements an interface which extends the original interface</li> <li>One of superclasses directly implements the interface</li> <li>One of superclasses implements an interface which extends the original interface</li> </ul> This is useful for logging purposes. @param clazz class to check whether implements the interface @param iface interface to be implemented @return <code>true</code> when the class implements the inteface with the same name
[ "Check", "whether", "given", "class", "implements", "an", "interface", "with", "the", "same", "name", ".", "It", "returns", "true", "even", "when", "the", "implemented", "interface", "is", "loaded", "by", "a", "different", "classloader", "and", "hence", "the", "class", "is", "not", "assignable", "into", "it", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/nio/ClassLoaderUtil.java#L356-L364
15,532
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterStateManager.java
ClusterStateManager.validateClusterVersionChange
private void validateClusterVersionChange(Version newClusterVersion) { if (!clusterVersion.isUnknown() && clusterVersion.getMajor() != newClusterVersion.getMajor()) { throw new IllegalArgumentException("Transition to requested version " + newClusterVersion + " not allowed for current cluster version " + clusterVersion); } }
java
private void validateClusterVersionChange(Version newClusterVersion) { if (!clusterVersion.isUnknown() && clusterVersion.getMajor() != newClusterVersion.getMajor()) { throw new IllegalArgumentException("Transition to requested version " + newClusterVersion + " not allowed for current cluster version " + clusterVersion); } }
[ "private", "void", "validateClusterVersionChange", "(", "Version", "newClusterVersion", ")", "{", "if", "(", "!", "clusterVersion", ".", "isUnknown", "(", ")", "&&", "clusterVersion", ".", "getMajor", "(", ")", "!=", "newClusterVersion", ".", "getMajor", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Transition to requested version \"", "+", "newClusterVersion", "+", "\" not allowed for current cluster version \"", "+", "clusterVersion", ")", ";", "}", "}" ]
validate transition from current to newClusterVersion is allowed
[ "validate", "transition", "from", "current", "to", "newClusterVersion", "is", "allowed" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterStateManager.java#L265-L270
15,533
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java
AbstractProxySessionManager.releaseSession
public final void releaseSession(RaftGroupId groupId, long id, int count) { SessionState session = sessions.get(groupId); if (session != null && session.id == id) { session.release(count); } }
java
public final void releaseSession(RaftGroupId groupId, long id, int count) { SessionState session = sessions.get(groupId); if (session != null && session.id == id) { session.release(count); } }
[ "public", "final", "void", "releaseSession", "(", "RaftGroupId", "groupId", ",", "long", "id", ",", "int", "count", ")", "{", "SessionState", "session", "=", "sessions", ".", "get", "(", "groupId", ")", ";", "if", "(", "session", "!=", "null", "&&", "session", ".", "id", "==", "id", ")", "{", "session", ".", "release", "(", "count", ")", ";", "}", "}" ]
Decrements acquire count of the session. Returns silently if no session exists for the given id.
[ "Decrements", "acquire", "count", "of", "the", "session", ".", "Returns", "silently", "if", "no", "session", "exists", "for", "the", "given", "id", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java#L145-L150
15,534
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java
AbstractProxySessionManager.invalidateSession
public final void invalidateSession(RaftGroupId groupId, long id) { SessionState session = sessions.get(groupId); if (session != null && session.id == id) { sessions.remove(groupId, session); } }
java
public final void invalidateSession(RaftGroupId groupId, long id) { SessionState session = sessions.get(groupId); if (session != null && session.id == id) { sessions.remove(groupId, session); } }
[ "public", "final", "void", "invalidateSession", "(", "RaftGroupId", "groupId", ",", "long", "id", ")", "{", "SessionState", "session", "=", "sessions", ".", "get", "(", "groupId", ")", ";", "if", "(", "session", "!=", "null", "&&", "session", ".", "id", "==", "id", ")", "{", "sessions", ".", "remove", "(", "groupId", ",", "session", ")", ";", "}", "}" ]
Invalidates the given session. No more heartbeats will be sent for the given session.
[ "Invalidates", "the", "given", "session", ".", "No", "more", "heartbeats", "will", "be", "sent", "for", "the", "given", "session", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java#L156-L161
15,535
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java
AbstractProxySessionManager.shutdown
public Map<RaftGroupId, ICompletableFuture<Object>> shutdown() { lock.writeLock().lock(); try { Map<RaftGroupId, ICompletableFuture<Object>> futures = new HashMap<RaftGroupId, ICompletableFuture<Object>>(); for (Entry<RaftGroupId, SessionState> e : sessions.entrySet()) { RaftGroupId groupId = e.getKey(); long sessionId = e.getValue().id; ICompletableFuture<Object> f = closeSession(groupId, sessionId); futures.put(groupId, f); } sessions.clear(); running = false; return futures; } finally { lock.writeLock().unlock(); } }
java
public Map<RaftGroupId, ICompletableFuture<Object>> shutdown() { lock.writeLock().lock(); try { Map<RaftGroupId, ICompletableFuture<Object>> futures = new HashMap<RaftGroupId, ICompletableFuture<Object>>(); for (Entry<RaftGroupId, SessionState> e : sessions.entrySet()) { RaftGroupId groupId = e.getKey(); long sessionId = e.getValue().id; ICompletableFuture<Object> f = closeSession(groupId, sessionId); futures.put(groupId, f); } sessions.clear(); running = false; return futures; } finally { lock.writeLock().unlock(); } }
[ "public", "Map", "<", "RaftGroupId", ",", "ICompletableFuture", "<", "Object", ">", ">", "shutdown", "(", ")", "{", "lock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "Map", "<", "RaftGroupId", ",", "ICompletableFuture", "<", "Object", ">", ">", "futures", "=", "new", "HashMap", "<", "RaftGroupId", ",", "ICompletableFuture", "<", "Object", ">", ">", "(", ")", ";", "for", "(", "Entry", "<", "RaftGroupId", ",", "SessionState", ">", "e", ":", "sessions", ".", "entrySet", "(", ")", ")", "{", "RaftGroupId", "groupId", "=", "e", ".", "getKey", "(", ")", ";", "long", "sessionId", "=", "e", ".", "getValue", "(", ")", ".", "id", ";", "ICompletableFuture", "<", "Object", ">", "f", "=", "closeSession", "(", "groupId", ",", "sessionId", ")", ";", "futures", ".", "put", "(", "groupId", ",", "f", ")", ";", "}", "sessions", ".", "clear", "(", ")", ";", "running", "=", "false", ";", "return", "futures", ";", "}", "finally", "{", "lock", ".", "writeLock", "(", ")", ".", "unlock", "(", ")", ";", "}", "}" ]
Invokes a shutdown call on server to close all existing sessions.
[ "Invokes", "a", "shutdown", "call", "on", "server", "to", "close", "all", "existing", "sessions", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java#L175-L191
15,536
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java
ProxyRegistry.getProxyInfos
public void getProxyInfos(Collection<ProxyInfo> result) { for (Map.Entry<String, DistributedObjectFuture> entry : proxies.entrySet()) { DistributedObjectFuture future = entry.getValue(); if (future.isSetAndInitialized()) { String proxyName = entry.getKey(); result.add(new ProxyInfo(serviceName, proxyName)); } } }
java
public void getProxyInfos(Collection<ProxyInfo> result) { for (Map.Entry<String, DistributedObjectFuture> entry : proxies.entrySet()) { DistributedObjectFuture future = entry.getValue(); if (future.isSetAndInitialized()) { String proxyName = entry.getKey(); result.add(new ProxyInfo(serviceName, proxyName)); } } }
[ "public", "void", "getProxyInfos", "(", "Collection", "<", "ProxyInfo", ">", "result", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "DistributedObjectFuture", ">", "entry", ":", "proxies", ".", "entrySet", "(", ")", ")", "{", "DistributedObjectFuture", "future", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "future", ".", "isSetAndInitialized", "(", ")", ")", "{", "String", "proxyName", "=", "entry", ".", "getKey", "(", ")", ";", "result", ".", "add", "(", "new", "ProxyInfo", "(", "serviceName", ",", "proxyName", ")", ")", ";", "}", "}", "}" ]
Gets the ProxyInfo of all fully initialized proxies in this registry. The result is written into 'result'. @param result The ProxyInfo of all proxies in this registry.
[ "Gets", "the", "ProxyInfo", "of", "all", "fully", "initialized", "proxies", "in", "this", "registry", ".", "The", "result", "is", "written", "into", "result", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java#L119-L127
15,537
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java
ProxyRegistry.getDistributedObjects
public void getDistributedObjects(Collection<DistributedObject> result) { Collection<DistributedObjectFuture> futures = proxies.values(); for (DistributedObjectFuture future : futures) { if (!future.isSetAndInitialized()) { continue; } try { DistributedObject object = future.get(); result.add(object); } catch (Throwable ignored) { // ignore if proxy creation failed ignore(ignored); } } }
java
public void getDistributedObjects(Collection<DistributedObject> result) { Collection<DistributedObjectFuture> futures = proxies.values(); for (DistributedObjectFuture future : futures) { if (!future.isSetAndInitialized()) { continue; } try { DistributedObject object = future.get(); result.add(object); } catch (Throwable ignored) { // ignore if proxy creation failed ignore(ignored); } } }
[ "public", "void", "getDistributedObjects", "(", "Collection", "<", "DistributedObject", ">", "result", ")", "{", "Collection", "<", "DistributedObjectFuture", ">", "futures", "=", "proxies", ".", "values", "(", ")", ";", "for", "(", "DistributedObjectFuture", "future", ":", "futures", ")", "{", "if", "(", "!", "future", ".", "isSetAndInitialized", "(", ")", ")", "{", "continue", ";", "}", "try", "{", "DistributedObject", "object", "=", "future", ".", "get", "(", ")", ";", "result", ".", "add", "(", "object", ")", ";", "}", "catch", "(", "Throwable", "ignored", ")", "{", "// ignore if proxy creation failed", "ignore", "(", "ignored", ")", ";", "}", "}", "}" ]
Gets the DistributedObjects in this registry. The result is written into 'result'. @param result The DistributedObjects in this registry.
[ "Gets", "the", "DistributedObjects", "in", "this", "registry", ".", "The", "result", "is", "written", "into", "result", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java#L134-L148
15,538
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java
ProxyRegistry.createProxy
public DistributedObjectFuture createProxy(String name, boolean publishEvent, boolean initialize) { if (proxies.containsKey(name)) { return null; } if (!proxyService.nodeEngine.isRunning()) { throw new HazelcastInstanceNotActiveException(); } DistributedObjectFuture proxyFuture = new DistributedObjectFuture(); if (proxies.putIfAbsent(name, proxyFuture) != null) { return null; } return doCreateProxy(name, publishEvent, initialize, proxyFuture); }
java
public DistributedObjectFuture createProxy(String name, boolean publishEvent, boolean initialize) { if (proxies.containsKey(name)) { return null; } if (!proxyService.nodeEngine.isRunning()) { throw new HazelcastInstanceNotActiveException(); } DistributedObjectFuture proxyFuture = new DistributedObjectFuture(); if (proxies.putIfAbsent(name, proxyFuture) != null) { return null; } return doCreateProxy(name, publishEvent, initialize, proxyFuture); }
[ "public", "DistributedObjectFuture", "createProxy", "(", "String", "name", ",", "boolean", "publishEvent", ",", "boolean", "initialize", ")", "{", "if", "(", "proxies", ".", "containsKey", "(", "name", ")", ")", "{", "return", "null", ";", "}", "if", "(", "!", "proxyService", ".", "nodeEngine", ".", "isRunning", "(", ")", ")", "{", "throw", "new", "HazelcastInstanceNotActiveException", "(", ")", ";", "}", "DistributedObjectFuture", "proxyFuture", "=", "new", "DistributedObjectFuture", "(", ")", ";", "if", "(", "proxies", ".", "putIfAbsent", "(", "name", ",", "proxyFuture", ")", "!=", "null", ")", "{", "return", "null", ";", "}", "return", "doCreateProxy", "(", "name", ",", "publishEvent", ",", "initialize", ",", "proxyFuture", ")", ";", "}" ]
Creates a DistributedObject proxy if it is not created yet @param name The name of the distributedObject proxy object. @param publishEvent true if a DistributedObjectEvent should be fired. @param initialize true if he DistributedObject proxy object should be initialized. @return The DistributedObject instance if it is created by this method, null otherwise.
[ "Creates", "a", "DistributedObject", "proxy", "if", "it", "is", "not", "created", "yet" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java#L195-L210
15,539
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java
ProxyRegistry.destroyProxy
void destroyProxy(String name, boolean publishEvent) { final DistributedObjectFuture proxyFuture = proxies.remove(name); if (proxyFuture == null) { return; } DistributedObject proxy; try { proxy = proxyFuture.get(); } catch (Throwable t) { proxyService.logger.warning("Cannot destroy proxy [" + serviceName + ":" + name + "], since its creation is failed with " + t.getClass().getName() + ": " + t.getMessage()); return; } InternalEventService eventService = proxyService.nodeEngine.getEventService(); ProxyEventProcessor callback = new ProxyEventProcessor(proxyService.listeners.values(), DESTROYED, serviceName, name, proxy); eventService.executeEventCallback(callback); if (publishEvent) { publish(new DistributedObjectEventPacket(DESTROYED, serviceName, name)); } }
java
void destroyProxy(String name, boolean publishEvent) { final DistributedObjectFuture proxyFuture = proxies.remove(name); if (proxyFuture == null) { return; } DistributedObject proxy; try { proxy = proxyFuture.get(); } catch (Throwable t) { proxyService.logger.warning("Cannot destroy proxy [" + serviceName + ":" + name + "], since its creation is failed with " + t.getClass().getName() + ": " + t.getMessage()); return; } InternalEventService eventService = proxyService.nodeEngine.getEventService(); ProxyEventProcessor callback = new ProxyEventProcessor(proxyService.listeners.values(), DESTROYED, serviceName, name, proxy); eventService.executeEventCallback(callback); if (publishEvent) { publish(new DistributedObjectEventPacket(DESTROYED, serviceName, name)); } }
[ "void", "destroyProxy", "(", "String", "name", ",", "boolean", "publishEvent", ")", "{", "final", "DistributedObjectFuture", "proxyFuture", "=", "proxies", ".", "remove", "(", "name", ")", ";", "if", "(", "proxyFuture", "==", "null", ")", "{", "return", ";", "}", "DistributedObject", "proxy", ";", "try", "{", "proxy", "=", "proxyFuture", ".", "get", "(", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "proxyService", ".", "logger", ".", "warning", "(", "\"Cannot destroy proxy [\"", "+", "serviceName", "+", "\":\"", "+", "name", "+", "\"], since its creation is failed with \"", "+", "t", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\": \"", "+", "t", ".", "getMessage", "(", ")", ")", ";", "return", ";", "}", "InternalEventService", "eventService", "=", "proxyService", ".", "nodeEngine", ".", "getEventService", "(", ")", ";", "ProxyEventProcessor", "callback", "=", "new", "ProxyEventProcessor", "(", "proxyService", ".", "listeners", ".", "values", "(", ")", ",", "DESTROYED", ",", "serviceName", ",", "name", ",", "proxy", ")", ";", "eventService", ".", "executeEventCallback", "(", "callback", ")", ";", "if", "(", "publishEvent", ")", "{", "publish", "(", "new", "DistributedObjectEventPacket", "(", "DESTROYED", ",", "serviceName", ",", "name", ")", ")", ";", "}", "}" ]
Destroys a proxy. @param name The name of the proxy to destroy. @param publishEvent true if this destroy should be published.
[ "Destroys", "a", "proxy", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java#L251-L273
15,540
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java
ProxyRegistry.destroy
void destroy() { for (DistributedObjectFuture future : proxies.values()) { if (!future.isSetAndInitialized()) { continue; } DistributedObject distributedObject = extractDistributedObject(future); invalidate(distributedObject); } proxies.clear(); }
java
void destroy() { for (DistributedObjectFuture future : proxies.values()) { if (!future.isSetAndInitialized()) { continue; } DistributedObject distributedObject = extractDistributedObject(future); invalidate(distributedObject); } proxies.clear(); }
[ "void", "destroy", "(", ")", "{", "for", "(", "DistributedObjectFuture", "future", ":", "proxies", ".", "values", "(", ")", ")", "{", "if", "(", "!", "future", ".", "isSetAndInitialized", "(", ")", ")", "{", "continue", ";", "}", "DistributedObject", "distributedObject", "=", "extractDistributedObject", "(", "future", ")", ";", "invalidate", "(", "distributedObject", ")", ";", "}", "proxies", ".", "clear", "(", ")", ";", "}" ]
Destroys this proxy registry.
[ "Destroys", "this", "proxy", "registry", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java#L285-L295
15,541
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/concurrent/BackoffIdleStrategy.java
BackoffIdleStrategy.createBackoffIdleStrategy
public static BackoffIdleStrategy createBackoffIdleStrategy(String config) { String[] args = config.split(","); if (args.length != ARG_COUNT) { throw new IllegalArgumentException( format("Invalid backoff configuration '%s', 4 arguments expected", config)); } long maxSpins = parseLong(args[ARG_MAX_SPINS]); long maxYields = parseLong(args[ARG_MAX_YIELDS]); long minParkPeriodNs = parseLong(args[ARG_MIN_PARK_PERIOD]); long maxParkNanos = parseLong(args[ARG_MAX_PARK_PERIOD]); return new BackoffIdleStrategy(maxSpins, maxYields, minParkPeriodNs, maxParkNanos); }
java
public static BackoffIdleStrategy createBackoffIdleStrategy(String config) { String[] args = config.split(","); if (args.length != ARG_COUNT) { throw new IllegalArgumentException( format("Invalid backoff configuration '%s', 4 arguments expected", config)); } long maxSpins = parseLong(args[ARG_MAX_SPINS]); long maxYields = parseLong(args[ARG_MAX_YIELDS]); long minParkPeriodNs = parseLong(args[ARG_MIN_PARK_PERIOD]); long maxParkNanos = parseLong(args[ARG_MAX_PARK_PERIOD]); return new BackoffIdleStrategy(maxSpins, maxYields, minParkPeriodNs, maxParkNanos); }
[ "public", "static", "BackoffIdleStrategy", "createBackoffIdleStrategy", "(", "String", "config", ")", "{", "String", "[", "]", "args", "=", "config", ".", "split", "(", "\",\"", ")", ";", "if", "(", "args", ".", "length", "!=", "ARG_COUNT", ")", "{", "throw", "new", "IllegalArgumentException", "(", "format", "(", "\"Invalid backoff configuration '%s', 4 arguments expected\"", ",", "config", ")", ")", ";", "}", "long", "maxSpins", "=", "parseLong", "(", "args", "[", "ARG_MAX_SPINS", "]", ")", ";", "long", "maxYields", "=", "parseLong", "(", "args", "[", "ARG_MAX_YIELDS", "]", ")", ";", "long", "minParkPeriodNs", "=", "parseLong", "(", "args", "[", "ARG_MIN_PARK_PERIOD", "]", ")", ";", "long", "maxParkNanos", "=", "parseLong", "(", "args", "[", "ARG_MAX_PARK_PERIOD", "]", ")", ";", "return", "new", "BackoffIdleStrategy", "(", "maxSpins", ",", "maxYields", ",", "minParkPeriodNs", ",", "maxParkNanos", ")", ";", "}" ]
Creates a new BackoffIdleStrategy.
[ "Creates", "a", "new", "BackoffIdleStrategy", "." ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/concurrent/BackoffIdleStrategy.java#L98-L109
15,542
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/networking/nio/NioInboundPipeline.java
NioInboundPipeline.pipelineToString
private String pipelineToString() { StringBuilder sb = new StringBuilder("in-pipeline["); InboundHandler[] handlers = this.handlers; for (int k = 0; k < handlers.length; k++) { if (k > 0) { sb.append("->-"); } sb.append(handlers[k].getClass().getSimpleName()); } sb.append(']'); return sb.toString(); }
java
private String pipelineToString() { StringBuilder sb = new StringBuilder("in-pipeline["); InboundHandler[] handlers = this.handlers; for (int k = 0; k < handlers.length; k++) { if (k > 0) { sb.append("->-"); } sb.append(handlers[k].getClass().getSimpleName()); } sb.append(']'); return sb.toString(); }
[ "private", "String", "pipelineToString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "\"in-pipeline[\"", ")", ";", "InboundHandler", "[", "]", "handlers", "=", "this", ".", "handlers", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "handlers", ".", "length", ";", "k", "++", ")", "{", "if", "(", "k", ">", "0", ")", "{", "sb", ".", "append", "(", "\"->-\"", ")", ";", "}", "sb", ".", "append", "(", "handlers", "[", "k", "]", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "}", "sb", ".", "append", "(", "'", "'", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
useful for debugging
[ "useful", "for", "debugging" ]
8c4bc10515dbbfb41a33e0302c0caedf3cda1baf
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/networking/nio/NioInboundPipeline.java#L254-L265
15,543
apollographql/apollo-android
apollo-api/src/main/java/com/apollographql/apollo/api/internal/Utils.java
Utils.checkNotNull
@NotNull public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; }
java
@NotNull public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; }
[ "@", "NotNull", "public", "static", "<", "T", ">", "T", "checkNotNull", "(", "T", "reference", ")", "{", "if", "(", "reference", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "return", "reference", ";", "}" ]
Checks if the object is null. Returns the object if it is not null, else throws a NullPointerException. @param reference the object whose nullability has to be checked @param <T> the value type @return The object itself @throws NullPointerException if the object is null
[ "Checks", "if", "the", "object", "is", "null", ".", "Returns", "the", "object", "if", "it", "is", "not", "null", "else", "throws", "a", "NullPointerException", "." ]
a78869a76e17f77e42c7a88f0099914fe7ffa5b6
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-api/src/main/java/com/apollographql/apollo/api/internal/Utils.java#L67-L72
15,544
apollographql/apollo-android
apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/ApolloCodegenInstallTask.java
ApolloCodegenInstallTask.getApolloVersion
private String getApolloVersion() { File packageFile = new File(getProject().getBuildDir(), INSTALL_DIR + "/package.json"); if (!packageFile.isFile()) { return null; } Moshi moshi = new Moshi.Builder().build(); JsonAdapter<PackageJson> adapter = moshi.adapter(PackageJson.class); try { PackageJson packageJson = adapter.fromJson(Okio.buffer(Okio.source(packageFile))); return packageJson.version; } catch (IOException e) { e.printStackTrace(); return null; } }
java
private String getApolloVersion() { File packageFile = new File(getProject().getBuildDir(), INSTALL_DIR + "/package.json"); if (!packageFile.isFile()) { return null; } Moshi moshi = new Moshi.Builder().build(); JsonAdapter<PackageJson> adapter = moshi.adapter(PackageJson.class); try { PackageJson packageJson = adapter.fromJson(Okio.buffer(Okio.source(packageFile))); return packageJson.version; } catch (IOException e) { e.printStackTrace(); return null; } }
[ "private", "String", "getApolloVersion", "(", ")", "{", "File", "packageFile", "=", "new", "File", "(", "getProject", "(", ")", ".", "getBuildDir", "(", ")", ",", "INSTALL_DIR", "+", "\"/package.json\"", ")", ";", "if", "(", "!", "packageFile", ".", "isFile", "(", ")", ")", "{", "return", "null", ";", "}", "Moshi", "moshi", "=", "new", "Moshi", ".", "Builder", "(", ")", ".", "build", "(", ")", ";", "JsonAdapter", "<", "PackageJson", ">", "adapter", "=", "moshi", ".", "adapter", "(", "PackageJson", ".", "class", ")", ";", "try", "{", "PackageJson", "packageJson", "=", "adapter", ".", "fromJson", "(", "Okio", ".", "buffer", "(", "Okio", ".", "source", "(", "packageFile", ")", ")", ")", ";", "return", "packageJson", ".", "version", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}" ]
Returns the locally install apollo-codegen version as found in the package.json file. @return null if build/apollo-codegen/node_modules/apollo-codegen/package.json wasn't found, version otherwise
[ "Returns", "the", "locally", "install", "apollo", "-", "codegen", "version", "as", "found", "in", "the", "package", ".", "json", "file", "." ]
a78869a76e17f77e42c7a88f0099914fe7ffa5b6
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/ApolloCodegenInstallTask.java#L68-L83
15,545
apollographql/apollo-android
apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/ApolloCodegenInstallTask.java
ApolloCodegenInstallTask.writePackageFile
private void writePackageFile(File apolloPackageFile) { try { JsonWriter writer = JsonWriter.of(Okio.buffer(Okio.sink(apolloPackageFile))); writer.beginObject(); writer.name("name").value("apollo-android"); writer.name("version").value("0.0.1"); writer.name("description").value("Generates Java code based on a GraphQL schema and query documents. Uses " + "apollo-codegen under the hood."); writer.name("name").value("apollo-android"); writer.name("repository"); writer.beginObject(); writer.name("type").value("git"); writer.name("url").value("git+https://github.com/apollostack/apollo-android.git"); writer.endObject(); writer.name("author").value("Apollo"); writer.name("license").value("MIT"); writer.endObject(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
java
private void writePackageFile(File apolloPackageFile) { try { JsonWriter writer = JsonWriter.of(Okio.buffer(Okio.sink(apolloPackageFile))); writer.beginObject(); writer.name("name").value("apollo-android"); writer.name("version").value("0.0.1"); writer.name("description").value("Generates Java code based on a GraphQL schema and query documents. Uses " + "apollo-codegen under the hood."); writer.name("name").value("apollo-android"); writer.name("repository"); writer.beginObject(); writer.name("type").value("git"); writer.name("url").value("git+https://github.com/apollostack/apollo-android.git"); writer.endObject(); writer.name("author").value("Apollo"); writer.name("license").value("MIT"); writer.endObject(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
[ "private", "void", "writePackageFile", "(", "File", "apolloPackageFile", ")", "{", "try", "{", "JsonWriter", "writer", "=", "JsonWriter", ".", "of", "(", "Okio", ".", "buffer", "(", "Okio", ".", "sink", "(", "apolloPackageFile", ")", ")", ")", ";", "writer", ".", "beginObject", "(", ")", ";", "writer", ".", "name", "(", "\"name\"", ")", ".", "value", "(", "\"apollo-android\"", ")", ";", "writer", ".", "name", "(", "\"version\"", ")", ".", "value", "(", "\"0.0.1\"", ")", ";", "writer", ".", "name", "(", "\"description\"", ")", ".", "value", "(", "\"Generates Java code based on a GraphQL schema and query documents. Uses \"", "+", "\"apollo-codegen under the hood.\"", ")", ";", "writer", ".", "name", "(", "\"name\"", ")", ".", "value", "(", "\"apollo-android\"", ")", ";", "writer", ".", "name", "(", "\"repository\"", ")", ";", "writer", ".", "beginObject", "(", ")", ";", "writer", ".", "name", "(", "\"type\"", ")", ".", "value", "(", "\"git\"", ")", ";", "writer", ".", "name", "(", "\"url\"", ")", ".", "value", "(", "\"git+https://github.com/apollostack/apollo-android.git\"", ")", ";", "writer", ".", "endObject", "(", ")", ";", "writer", ".", "name", "(", "\"author\"", ")", ".", "value", "(", "\"Apollo\"", ")", ";", "writer", ".", "name", "(", "\"license\"", ")", ".", "value", "(", "\"MIT\"", ")", ";", "writer", ".", "endObject", "(", ")", ";", "writer", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Generates a dummy package.json file to silence npm warnings
[ "Generates", "a", "dummy", "package", ".", "json", "file", "to", "silence", "npm", "warnings" ]
a78869a76e17f77e42c7a88f0099914fe7ffa5b6
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/ApolloCodegenInstallTask.java#L91-L115
15,546
apollographql/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo/cache/normalized/ApolloStoreOperation.java
ApolloStoreOperation.enqueue
public void enqueue(@Nullable final Callback<T> callback) { checkIfExecuted(); this.callback.set(callback); dispatcher.execute(new Runnable() { @Override public void run() { T result; try { result = perform(); } catch (Exception e) { notifyFailure(new ApolloException("Failed to perform store operation", e)); return; } notifySuccess(result); } }); }
java
public void enqueue(@Nullable final Callback<T> callback) { checkIfExecuted(); this.callback.set(callback); dispatcher.execute(new Runnable() { @Override public void run() { T result; try { result = perform(); } catch (Exception e) { notifyFailure(new ApolloException("Failed to perform store operation", e)); return; } notifySuccess(result); } }); }
[ "public", "void", "enqueue", "(", "@", "Nullable", "final", "Callback", "<", "T", ">", "callback", ")", "{", "checkIfExecuted", "(", ")", ";", "this", ".", "callback", ".", "set", "(", "callback", ")", ";", "dispatcher", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "T", "result", ";", "try", "{", "result", "=", "perform", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "notifyFailure", "(", "new", "ApolloException", "(", "\"Failed to perform store operation\"", ",", "e", ")", ")", ";", "return", ";", "}", "notifySuccess", "(", "result", ")", ";", "}", "}", ")", ";", "}" ]
Schedules operation to be executed in dispatcher @param callback to be notified about operation result
[ "Schedules", "operation", "to", "be", "executed", "in", "dispatcher" ]
a78869a76e17f77e42c7a88f0099914fe7ffa5b6
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-runtime/src/main/java/com/apollographql/apollo/cache/normalized/ApolloStoreOperation.java#L69-L85
15,547
apollographql/apollo-android
apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/CodegenGenerationTaskCommandArgsBuilder.java
CodegenGenerationTaskCommandArgsBuilder.getSourceSetNameFromFile
private String getSourceSetNameFromFile(File file) { Path absolutePath = Paths.get(file.getAbsolutePath()); Path basePath = Paths.get(task.getProject().file("src").getAbsolutePath()); return basePath.relativize(absolutePath).toString().split(Matcher.quoteReplacement(File.separator))[0]; }
java
private String getSourceSetNameFromFile(File file) { Path absolutePath = Paths.get(file.getAbsolutePath()); Path basePath = Paths.get(task.getProject().file("src").getAbsolutePath()); return basePath.relativize(absolutePath).toString().split(Matcher.quoteReplacement(File.separator))[0]; }
[ "private", "String", "getSourceSetNameFromFile", "(", "File", "file", ")", "{", "Path", "absolutePath", "=", "Paths", ".", "get", "(", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "Path", "basePath", "=", "Paths", ".", "get", "(", "task", ".", "getProject", "(", ")", ".", "file", "(", "\"src\"", ")", ".", "getAbsolutePath", "(", ")", ")", ";", "return", "basePath", ".", "relativize", "(", "absolutePath", ")", ".", "toString", "(", ")", ".", "split", "(", "Matcher", ".", "quoteReplacement", "(", "File", ".", "separator", ")", ")", "[", "0", "]", ";", "}" ]
Returns the source set folder name given a file path. Assumes the source set name follows the "src" folder based on the inputs received from GraphQLSourceDirectorySet. @return - sourceSet name
[ "Returns", "the", "source", "set", "folder", "name", "given", "a", "file", "path", ".", "Assumes", "the", "source", "set", "name", "follows", "the", "src", "folder", "based", "on", "the", "inputs", "received", "from", "GraphQLSourceDirectorySet", "." ]
a78869a76e17f77e42c7a88f0099914fe7ffa5b6
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/CodegenGenerationTaskCommandArgsBuilder.java#L206-L211
15,548
apollographql/apollo-android
apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/CodegenGenerationTaskCommandArgsBuilder.java
CodegenGenerationTaskCommandArgsBuilder.getPathRelativeToSourceSet
private String getPathRelativeToSourceSet(File file) { Path absolutePath = Paths.get(file.getAbsolutePath()); Path basePath = Paths.get(task.getProject().file("src").getAbsolutePath() + File.separator + getSourceSetNameFromFile(file)); return basePath.relativize(absolutePath).toString(); }
java
private String getPathRelativeToSourceSet(File file) { Path absolutePath = Paths.get(file.getAbsolutePath()); Path basePath = Paths.get(task.getProject().file("src").getAbsolutePath() + File.separator + getSourceSetNameFromFile(file)); return basePath.relativize(absolutePath).toString(); }
[ "private", "String", "getPathRelativeToSourceSet", "(", "File", "file", ")", "{", "Path", "absolutePath", "=", "Paths", ".", "get", "(", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "Path", "basePath", "=", "Paths", ".", "get", "(", "task", ".", "getProject", "(", ")", ".", "file", "(", "\"src\"", ")", ".", "getAbsolutePath", "(", ")", "+", "File", ".", "separator", "+", "getSourceSetNameFromFile", "(", "file", ")", ")", ";", "return", "basePath", ".", "relativize", "(", "absolutePath", ")", ".", "toString", "(", ")", ";", "}" ]
Returns the file path relative to the sourceSet directory @return path relative to sourceSet directory
[ "Returns", "the", "file", "path", "relative", "to", "the", "sourceSet", "directory" ]
a78869a76e17f77e42c7a88f0099914fe7ffa5b6
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/CodegenGenerationTaskCommandArgsBuilder.java#L218-L222
15,549
apollographql/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo/cache/normalized/Record.java
Record.referencedFields
public List<CacheReference> referencedFields() { List<CacheReference> cacheReferences = new ArrayList<>(); for (Object value : fields.values()) { findCacheReferences(value, cacheReferences); } return cacheReferences; }
java
public List<CacheReference> referencedFields() { List<CacheReference> cacheReferences = new ArrayList<>(); for (Object value : fields.values()) { findCacheReferences(value, cacheReferences); } return cacheReferences; }
[ "public", "List", "<", "CacheReference", ">", "referencedFields", "(", ")", "{", "List", "<", "CacheReference", ">", "cacheReferences", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Object", "value", ":", "fields", ".", "values", "(", ")", ")", "{", "findCacheReferences", "(", "value", ",", "cacheReferences", ")", ";", "}", "return", "cacheReferences", ";", "}" ]
Returns the list of referenced cache fields @return the list of referenced cache fields
[ "Returns", "the", "list", "of", "referenced", "cache", "fields" ]
a78869a76e17f77e42c7a88f0099914fe7ffa5b6
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-runtime/src/main/java/com/apollographql/apollo/cache/normalized/Record.java#L156-L162
15,550
jhalterman/failsafe
src/main/java/net/jodah/failsafe/PolicyExecutor.java
PolicyExecutor.supply
protected Supplier<ExecutionResult> supply(Supplier<ExecutionResult> supplier) { return () -> { ExecutionResult result = preExecute(); if (result != null) return result; return postExecute(supplier.get()); }; }
java
protected Supplier<ExecutionResult> supply(Supplier<ExecutionResult> supplier) { return () -> { ExecutionResult result = preExecute(); if (result != null) return result; return postExecute(supplier.get()); }; }
[ "protected", "Supplier", "<", "ExecutionResult", ">", "supply", "(", "Supplier", "<", "ExecutionResult", ">", "supplier", ")", "{", "return", "(", ")", "->", "{", "ExecutionResult", "result", "=", "preExecute", "(", ")", ";", "if", "(", "result", "!=", "null", ")", "return", "result", ";", "return", "postExecute", "(", "supplier", ".", "get", "(", ")", ")", ";", "}", ";", "}" ]
Performs a synchronous execution by first doing a pre-execute, calling the next executor, else calling the executor's supplier, then finally doing a post-execute.
[ "Performs", "a", "synchronous", "execution", "by", "first", "doing", "a", "pre", "-", "execute", "calling", "the", "next", "executor", "else", "calling", "the", "executor", "s", "supplier", "then", "finally", "doing", "a", "post", "-", "execute", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/PolicyExecutor.java#L51-L59
15,551
jhalterman/failsafe
src/main/java/net/jodah/failsafe/PolicyExecutor.java
PolicyExecutor.supplyAsync
protected Supplier<CompletableFuture<ExecutionResult>> supplyAsync( Supplier<CompletableFuture<ExecutionResult>> supplier, Scheduler scheduler, FailsafeFuture<Object> future) { return () -> { ExecutionResult result = preExecute(); if (result != null) return CompletableFuture.completedFuture(result); return supplier.get().thenCompose(s -> postExecuteAsync(s, scheduler, future)); }; }
java
protected Supplier<CompletableFuture<ExecutionResult>> supplyAsync( Supplier<CompletableFuture<ExecutionResult>> supplier, Scheduler scheduler, FailsafeFuture<Object> future) { return () -> { ExecutionResult result = preExecute(); if (result != null) return CompletableFuture.completedFuture(result); return supplier.get().thenCompose(s -> postExecuteAsync(s, scheduler, future)); }; }
[ "protected", "Supplier", "<", "CompletableFuture", "<", "ExecutionResult", ">", ">", "supplyAsync", "(", "Supplier", "<", "CompletableFuture", "<", "ExecutionResult", ">", ">", "supplier", ",", "Scheduler", "scheduler", ",", "FailsafeFuture", "<", "Object", ">", "future", ")", "{", "return", "(", ")", "->", "{", "ExecutionResult", "result", "=", "preExecute", "(", ")", ";", "if", "(", "result", "!=", "null", ")", "return", "CompletableFuture", ".", "completedFuture", "(", "result", ")", ";", "return", "supplier", ".", "get", "(", ")", ".", "thenCompose", "(", "s", "->", "postExecuteAsync", "(", "s", ",", "scheduler", ",", "future", ")", ")", ";", "}", ";", "}" ]
Performs an async execution by first doing an optional pre-execute, calling the next executor, else scheduling the executor's supplier, then finally doing an async post-execute.
[ "Performs", "an", "async", "execution", "by", "first", "doing", "an", "optional", "pre", "-", "execute", "calling", "the", "next", "executor", "else", "scheduling", "the", "executor", "s", "supplier", "then", "finally", "doing", "an", "async", "post", "-", "execute", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/PolicyExecutor.java#L81-L90
15,552
jhalterman/failsafe
src/main/java/net/jodah/failsafe/CircuitBreaker.java
CircuitBreaker.withFailureThreshold
public CircuitBreaker<R> withFailureThreshold(int failureThreshold) { Assert.isTrue(failureThreshold >= 1, "failureThreshold must be greater than or equal to 1"); return withFailureThreshold(failureThreshold, failureThreshold); }
java
public CircuitBreaker<R> withFailureThreshold(int failureThreshold) { Assert.isTrue(failureThreshold >= 1, "failureThreshold must be greater than or equal to 1"); return withFailureThreshold(failureThreshold, failureThreshold); }
[ "public", "CircuitBreaker", "<", "R", ">", "withFailureThreshold", "(", "int", "failureThreshold", ")", "{", "Assert", ".", "isTrue", "(", "failureThreshold", ">=", "1", ",", "\"failureThreshold must be greater than or equal to 1\"", ")", ";", "return", "withFailureThreshold", "(", "failureThreshold", ",", "failureThreshold", ")", ";", "}" ]
Sets the number of successive failures that must occur when in a closed state in order to open the circuit. @throws IllegalArgumentException if {@code failureThresh} < 1
[ "Sets", "the", "number", "of", "successive", "failures", "that", "must", "occur", "when", "in", "a", "closed", "state", "in", "order", "to", "open", "the", "circuit", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/CircuitBreaker.java#L298-L301
15,553
jhalterman/failsafe
src/main/java/net/jodah/failsafe/CircuitBreaker.java
CircuitBreaker.withSuccessThreshold
public CircuitBreaker<R> withSuccessThreshold(int successThreshold) { Assert.isTrue(successThreshold >= 1, "successThreshold must be greater than or equal to 1"); return withSuccessThreshold(successThreshold, successThreshold); }
java
public CircuitBreaker<R> withSuccessThreshold(int successThreshold) { Assert.isTrue(successThreshold >= 1, "successThreshold must be greater than or equal to 1"); return withSuccessThreshold(successThreshold, successThreshold); }
[ "public", "CircuitBreaker", "<", "R", ">", "withSuccessThreshold", "(", "int", "successThreshold", ")", "{", "Assert", ".", "isTrue", "(", "successThreshold", ">=", "1", ",", "\"successThreshold must be greater than or equal to 1\"", ")", ";", "return", "withSuccessThreshold", "(", "successThreshold", ",", "successThreshold", ")", ";", "}" ]
Sets the number of successive successful executions that must occur when in a half-open state in order to close the circuit, else the circuit is re-opened when a failure occurs. @throws IllegalArgumentException if {@code successThreshold} < 1
[ "Sets", "the", "number", "of", "successive", "successful", "executions", "that", "must", "occur", "when", "in", "a", "half", "-", "open", "state", "in", "order", "to", "close", "the", "circuit", "else", "the", "circuit", "is", "re", "-", "opened", "when", "a", "failure", "occurs", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/CircuitBreaker.java#L328-L331
15,554
jhalterman/failsafe
src/main/java/net/jodah/failsafe/internal/util/CircularBitSet.java
CircularBitSet.setNext
public synchronized int setNext(boolean value) { int previousValue = -1; if (occupiedBits < size) occupiedBits++; else previousValue = bitSet.get(nextIndex) ? 1 : 0; bitSet.set(nextIndex, value); nextIndex = indexAfter(nextIndex); if (value) { if (previousValue != 1) positives++; if (previousValue == 0) negatives--; } else { if (previousValue != 0) negatives++; if (previousValue == 1) positives--; } return previousValue; }
java
public synchronized int setNext(boolean value) { int previousValue = -1; if (occupiedBits < size) occupiedBits++; else previousValue = bitSet.get(nextIndex) ? 1 : 0; bitSet.set(nextIndex, value); nextIndex = indexAfter(nextIndex); if (value) { if (previousValue != 1) positives++; if (previousValue == 0) negatives--; } else { if (previousValue != 0) negatives++; if (previousValue == 1) positives--; } return previousValue; }
[ "public", "synchronized", "int", "setNext", "(", "boolean", "value", ")", "{", "int", "previousValue", "=", "-", "1", ";", "if", "(", "occupiedBits", "<", "size", ")", "occupiedBits", "++", ";", "else", "previousValue", "=", "bitSet", ".", "get", "(", "nextIndex", ")", "?", "1", ":", "0", ";", "bitSet", ".", "set", "(", "nextIndex", ",", "value", ")", ";", "nextIndex", "=", "indexAfter", "(", "nextIndex", ")", ";", "if", "(", "value", ")", "{", "if", "(", "previousValue", "!=", "1", ")", "positives", "++", ";", "if", "(", "previousValue", "==", "0", ")", "negatives", "--", ";", "}", "else", "{", "if", "(", "previousValue", "!=", "0", ")", "negatives", "++", ";", "if", "(", "previousValue", "==", "1", ")", "positives", "--", ";", "}", "return", "previousValue", ";", "}" ]
Sets the value of the next bit in the bitset, returning the previous value, else -1 if no previous value was set for the bit. @param value true if positive/success, false if negative/failure
[ "Sets", "the", "value", "of", "the", "next", "bit", "in", "the", "bitset", "returning", "the", "previous", "value", "else", "-", "1", "if", "no", "previous", "value", "was", "set", "for", "the", "bit", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/internal/util/CircularBitSet.java#L116-L139
15,555
jhalterman/failsafe
src/main/java/net/jodah/failsafe/internal/HalfOpenState.java
HalfOpenState.maxConcurrentExecutions
int maxConcurrentExecutions() { if (circuit.getSuccessThreshold() != null) return circuit.getSuccessThreshold().getDenominator(); else if (circuit.getFailureThreshold() != null) return circuit.getFailureThreshold().getDenominator(); else return 1; }
java
int maxConcurrentExecutions() { if (circuit.getSuccessThreshold() != null) return circuit.getSuccessThreshold().getDenominator(); else if (circuit.getFailureThreshold() != null) return circuit.getFailureThreshold().getDenominator(); else return 1; }
[ "int", "maxConcurrentExecutions", "(", ")", "{", "if", "(", "circuit", ".", "getSuccessThreshold", "(", ")", "!=", "null", ")", "return", "circuit", ".", "getSuccessThreshold", "(", ")", ".", "getDenominator", "(", ")", ";", "else", "if", "(", "circuit", ".", "getFailureThreshold", "(", ")", "!=", "null", ")", "return", "circuit", ".", "getFailureThreshold", "(", ")", ".", "getDenominator", "(", ")", ";", "else", "return", "1", ";", "}" ]
Returns the max allowed concurrent executions.
[ "Returns", "the", "max", "allowed", "concurrent", "executions", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/internal/HalfOpenState.java#L107-L114
15,556
jhalterman/failsafe
src/main/java/net/jodah/failsafe/ExecutionResult.java
ExecutionResult.withComplete
public ExecutionResult withComplete() { return this.complete ? this : new ExecutionResult(result, failure, nonResult, waitNanos, true, success, successAll); }
java
public ExecutionResult withComplete() { return this.complete ? this : new ExecutionResult(result, failure, nonResult, waitNanos, true, success, successAll); }
[ "public", "ExecutionResult", "withComplete", "(", ")", "{", "return", "this", ".", "complete", "?", "this", ":", "new", "ExecutionResult", "(", "result", ",", "failure", ",", "nonResult", ",", "waitNanos", ",", "true", ",", "success", ",", "successAll", ")", ";", "}" ]
Returns a copy of the ExecutionResult with the value set to true, else this if nothing has changed.
[ "Returns", "a", "copy", "of", "the", "ExecutionResult", "with", "the", "value", "set", "to", "true", "else", "this", "if", "nothing", "has", "changed", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/ExecutionResult.java#L110-L112
15,557
jhalterman/failsafe
src/main/java/net/jodah/failsafe/RetryPolicy.java
RetryPolicy.isAbortable
public boolean isAbortable(R result, Throwable failure) { for (BiPredicate<R, Throwable> predicate : abortConditions) { try { if (predicate.test(result, failure)) return true; } catch (Exception t) { // Ignore confused user-supplied predicates. // They should not be allowed to halt execution of the operation. } } return false; }
java
public boolean isAbortable(R result, Throwable failure) { for (BiPredicate<R, Throwable> predicate : abortConditions) { try { if (predicate.test(result, failure)) return true; } catch (Exception t) { // Ignore confused user-supplied predicates. // They should not be allowed to halt execution of the operation. } } return false; }
[ "public", "boolean", "isAbortable", "(", "R", "result", ",", "Throwable", "failure", ")", "{", "for", "(", "BiPredicate", "<", "R", ",", "Throwable", ">", "predicate", ":", "abortConditions", ")", "{", "try", "{", "if", "(", "predicate", ".", "test", "(", "result", ",", "failure", ")", ")", "return", "true", ";", "}", "catch", "(", "Exception", "t", ")", "{", "// Ignore confused user-supplied predicates.", "// They should not be allowed to halt execution of the operation.", "}", "}", "return", "false", ";", "}" ]
Returns whether an execution result can be aborted given the configured abort conditions. @see #abortOn(Class...) @see #abortOn(List) @see #abortOn(Predicate) @see #abortIf(BiPredicate) @see #abortIf(Predicate) @see #abortWhen(R)
[ "Returns", "whether", "an", "execution", "result", "can", "be", "aborted", "given", "the", "configured", "abort", "conditions", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/RetryPolicy.java#L243-L254
15,558
jhalterman/failsafe
src/main/java/net/jodah/failsafe/RetryPolicy.java
RetryPolicy.canApplyDelayFn
public boolean canApplyDelayFn(R result, Throwable failure) { return (delayResult == null || delayResult.equals(result)) && (delayFailure == null || (failure != null && delayFailure.isAssignableFrom(failure.getClass()))); }
java
public boolean canApplyDelayFn(R result, Throwable failure) { return (delayResult == null || delayResult.equals(result)) && (delayFailure == null || (failure != null && delayFailure.isAssignableFrom(failure.getClass()))); }
[ "public", "boolean", "canApplyDelayFn", "(", "R", "result", ",", "Throwable", "failure", ")", "{", "return", "(", "delayResult", "==", "null", "||", "delayResult", ".", "equals", "(", "result", ")", ")", "&&", "(", "delayFailure", "==", "null", "||", "(", "failure", "!=", "null", "&&", "delayFailure", ".", "isAssignableFrom", "(", "failure", ".", "getClass", "(", ")", ")", ")", ")", ";", "}" ]
Returns whether any configured delay function can be applied for an execution result. @see #withDelay(DelayFunction) @see #withDelayOn(DelayFunction, Class) @see #withDelayWhen(DelayFunction, Object)
[ "Returns", "whether", "any", "configured", "delay", "function", "can", "be", "applied", "for", "an", "execution", "result", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/RetryPolicy.java#L296-L299
15,559
jhalterman/failsafe
src/main/java/net/jodah/failsafe/RetryPolicy.java
RetryPolicy.withMaxDuration
public RetryPolicy<R> withMaxDuration(Duration maxDuration) { Assert.notNull(maxDuration, "maxDuration"); Assert.state(maxDuration.toNanos() > delay.toNanos(), "maxDuration must be greater than the delay"); this.maxDuration = maxDuration; return this; }
java
public RetryPolicy<R> withMaxDuration(Duration maxDuration) { Assert.notNull(maxDuration, "maxDuration"); Assert.state(maxDuration.toNanos() > delay.toNanos(), "maxDuration must be greater than the delay"); this.maxDuration = maxDuration; return this; }
[ "public", "RetryPolicy", "<", "R", ">", "withMaxDuration", "(", "Duration", "maxDuration", ")", "{", "Assert", ".", "notNull", "(", "maxDuration", ",", "\"maxDuration\"", ")", ";", "Assert", ".", "state", "(", "maxDuration", ".", "toNanos", "(", ")", ">", "delay", ".", "toNanos", "(", ")", ",", "\"maxDuration must be greater than the delay\"", ")", ";", "this", ".", "maxDuration", "=", "maxDuration", ";", "return", "this", ";", "}" ]
Sets the max duration to perform retries for, else the execution will be failed. @throws NullPointerException if {@code maxDuration} is null @throws IllegalStateException if {@code maxDuration} is <= the {@link RetryPolicy#withDelay(Duration) delay}
[ "Sets", "the", "max", "duration", "to", "perform", "retries", "for", "else", "the", "execution", "will", "be", "failed", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/RetryPolicy.java#L609-L614
15,560
jhalterman/failsafe
src/main/java/net/jodah/failsafe/FailsafeFuture.java
FailsafeFuture.cancel
@Override public synchronized boolean cancel(boolean mayInterruptIfRunning) { if (isDone()) return false; boolean cancelResult = super.cancel(mayInterruptIfRunning); if (delegate != null) cancelResult = delegate.cancel(mayInterruptIfRunning); Throwable failure = new CancellationException(); complete(null, failure); executor.handleComplete(ExecutionResult.failure(failure), execution); return cancelResult; }
java
@Override public synchronized boolean cancel(boolean mayInterruptIfRunning) { if (isDone()) return false; boolean cancelResult = super.cancel(mayInterruptIfRunning); if (delegate != null) cancelResult = delegate.cancel(mayInterruptIfRunning); Throwable failure = new CancellationException(); complete(null, failure); executor.handleComplete(ExecutionResult.failure(failure), execution); return cancelResult; }
[ "@", "Override", "public", "synchronized", "boolean", "cancel", "(", "boolean", "mayInterruptIfRunning", ")", "{", "if", "(", "isDone", "(", ")", ")", "return", "false", ";", "boolean", "cancelResult", "=", "super", ".", "cancel", "(", "mayInterruptIfRunning", ")", ";", "if", "(", "delegate", "!=", "null", ")", "cancelResult", "=", "delegate", ".", "cancel", "(", "mayInterruptIfRunning", ")", ";", "Throwable", "failure", "=", "new", "CancellationException", "(", ")", ";", "complete", "(", "null", ",", "failure", ")", ";", "executor", ".", "handleComplete", "(", "ExecutionResult", ".", "failure", "(", "failure", ")", ",", "execution", ")", ";", "return", "cancelResult", ";", "}" ]
Cancels this and the internal delegate.
[ "Cancels", "this", "and", "the", "internal", "delegate", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/FailsafeFuture.java#L42-L54
15,561
jhalterman/failsafe
src/main/java/net/jodah/failsafe/Execution.java
Execution.executeSync
ExecutionResult executeSync(Supplier<ExecutionResult> supplier) { for (PolicyExecutor<Policy<Object>> policyExecutor : policyExecutors) supplier = policyExecutor.supply(supplier); ExecutionResult result = supplier.get(); completed = result.isComplete(); executor.handleComplete(result, this); return result; }
java
ExecutionResult executeSync(Supplier<ExecutionResult> supplier) { for (PolicyExecutor<Policy<Object>> policyExecutor : policyExecutors) supplier = policyExecutor.supply(supplier); ExecutionResult result = supplier.get(); completed = result.isComplete(); executor.handleComplete(result, this); return result; }
[ "ExecutionResult", "executeSync", "(", "Supplier", "<", "ExecutionResult", ">", "supplier", ")", "{", "for", "(", "PolicyExecutor", "<", "Policy", "<", "Object", ">", ">", "policyExecutor", ":", "policyExecutors", ")", "supplier", "=", "policyExecutor", ".", "supply", "(", "supplier", ")", ";", "ExecutionResult", "result", "=", "supplier", ".", "get", "(", ")", ";", "completed", "=", "result", ".", "isComplete", "(", ")", ";", "executor", ".", "handleComplete", "(", "result", ",", "this", ")", ";", "return", "result", ";", "}" ]
Performs a synchronous execution.
[ "Performs", "a", "synchronous", "execution", "." ]
65fcd3a82f7b232d2ff59bc525a59d693dd8e223
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/Execution.java#L114-L122
15,562
Karumi/Dexter
dexter/src/main/java/com/karumi/dexter/MultiplePermissionsReport.java
MultiplePermissionsReport.isAnyPermissionPermanentlyDenied
public boolean isAnyPermissionPermanentlyDenied() { boolean hasPermanentlyDeniedAnyPermission = false; for (PermissionDeniedResponse deniedResponse : deniedPermissionResponses) { if (deniedResponse.isPermanentlyDenied()) { hasPermanentlyDeniedAnyPermission = true; break; } } return hasPermanentlyDeniedAnyPermission; }
java
public boolean isAnyPermissionPermanentlyDenied() { boolean hasPermanentlyDeniedAnyPermission = false; for (PermissionDeniedResponse deniedResponse : deniedPermissionResponses) { if (deniedResponse.isPermanentlyDenied()) { hasPermanentlyDeniedAnyPermission = true; break; } } return hasPermanentlyDeniedAnyPermission; }
[ "public", "boolean", "isAnyPermissionPermanentlyDenied", "(", ")", "{", "boolean", "hasPermanentlyDeniedAnyPermission", "=", "false", ";", "for", "(", "PermissionDeniedResponse", "deniedResponse", ":", "deniedPermissionResponses", ")", "{", "if", "(", "deniedResponse", ".", "isPermanentlyDenied", "(", ")", ")", "{", "hasPermanentlyDeniedAnyPermission", "=", "true", ";", "break", ";", "}", "}", "return", "hasPermanentlyDeniedAnyPermission", ";", "}" ]
Returns whether the user has permanently denied any of the requested permissions
[ "Returns", "whether", "the", "user", "has", "permanently", "denied", "any", "of", "the", "requested", "permissions" ]
11cfa35a2eaa51f01f6678adb69bed0382a867e7
https://github.com/Karumi/Dexter/blob/11cfa35a2eaa51f01f6678adb69bed0382a867e7/dexter/src/main/java/com/karumi/dexter/MultiplePermissionsReport.java#L61-L72
15,563
Karumi/Dexter
dexter/src/main/java/com/karumi/dexter/DexterInstance.java
DexterInstance.checkPermission
void checkPermission(PermissionListener listener, String permission, Thread thread) { checkSinglePermission(listener, permission, thread); }
java
void checkPermission(PermissionListener listener, String permission, Thread thread) { checkSinglePermission(listener, permission, thread); }
[ "void", "checkPermission", "(", "PermissionListener", "listener", ",", "String", "permission", ",", "Thread", "thread", ")", "{", "checkSinglePermission", "(", "listener", ",", "permission", ",", "thread", ")", ";", "}" ]
Checks the state of a specific permission reporting it when ready to the listener. @param listener The class that will be reported when the state of the permission is ready @param permission One of the values found in {@link android.Manifest.permission} @param thread thread the Listener methods will be called on
[ "Checks", "the", "state", "of", "a", "specific", "permission", "reporting", "it", "when", "ready", "to", "the", "listener", "." ]
11cfa35a2eaa51f01f6678adb69bed0382a867e7
https://github.com/Karumi/Dexter/blob/11cfa35a2eaa51f01f6678adb69bed0382a867e7/dexter/src/main/java/com/karumi/dexter/DexterInstance.java#L85-L87
15,564
Karumi/Dexter
dexter/src/main/java/com/karumi/dexter/DexterInstance.java
DexterInstance.checkPermissions
void checkPermissions(MultiplePermissionsListener listener, Collection<String> permissions, Thread thread) { checkMultiplePermissions(listener, permissions, thread); }
java
void checkPermissions(MultiplePermissionsListener listener, Collection<String> permissions, Thread thread) { checkMultiplePermissions(listener, permissions, thread); }
[ "void", "checkPermissions", "(", "MultiplePermissionsListener", "listener", ",", "Collection", "<", "String", ">", "permissions", ",", "Thread", "thread", ")", "{", "checkMultiplePermissions", "(", "listener", ",", "permissions", ",", "thread", ")", ";", "}" ]
Checks the state of a collection of permissions reporting their state to the listener when all of them are resolved @param listener The class that will be reported when the state of all the permissions is ready @param permissions Array of values found in {@link android.Manifest.permission} @param thread thread the Listener methods will be called on
[ "Checks", "the", "state", "of", "a", "collection", "of", "permissions", "reporting", "their", "state", "to", "the", "listener", "when", "all", "of", "them", "are", "resolved" ]
11cfa35a2eaa51f01f6678adb69bed0382a867e7
https://github.com/Karumi/Dexter/blob/11cfa35a2eaa51f01f6678adb69bed0382a867e7/dexter/src/main/java/com/karumi/dexter/DexterInstance.java#L97-L100
15,565
Karumi/Dexter
dexter/src/main/java/com/karumi/dexter/DexterInstance.java
DexterInstance.onActivityReady
void onActivityReady(Activity activity) { this.activity = activity; PermissionStates permissionStates = null; synchronized (pendingPermissionsMutex) { if (activity != null) { permissionStates = getPermissionStates(pendingPermissions); } } if (permissionStates != null) { handleDeniedPermissions(permissionStates.getDeniedPermissions()); updatePermissionsAsDenied(permissionStates.getImpossibleToGrantPermissions()); updatePermissionsAsGranted(permissionStates.getGrantedPermissions()); } }
java
void onActivityReady(Activity activity) { this.activity = activity; PermissionStates permissionStates = null; synchronized (pendingPermissionsMutex) { if (activity != null) { permissionStates = getPermissionStates(pendingPermissions); } } if (permissionStates != null) { handleDeniedPermissions(permissionStates.getDeniedPermissions()); updatePermissionsAsDenied(permissionStates.getImpossibleToGrantPermissions()); updatePermissionsAsGranted(permissionStates.getGrantedPermissions()); } }
[ "void", "onActivityReady", "(", "Activity", "activity", ")", "{", "this", ".", "activity", "=", "activity", ";", "PermissionStates", "permissionStates", "=", "null", ";", "synchronized", "(", "pendingPermissionsMutex", ")", "{", "if", "(", "activity", "!=", "null", ")", "{", "permissionStates", "=", "getPermissionStates", "(", "pendingPermissions", ")", ";", "}", "}", "if", "(", "permissionStates", "!=", "null", ")", "{", "handleDeniedPermissions", "(", "permissionStates", ".", "getDeniedPermissions", "(", ")", ")", ";", "updatePermissionsAsDenied", "(", "permissionStates", ".", "getImpossibleToGrantPermissions", "(", ")", ")", ";", "updatePermissionsAsGranted", "(", "permissionStates", ".", "getGrantedPermissions", "(", ")", ")", ";", "}", "}" ]
Method called whenever the inner activity has been created or restarted and is ready to be used.
[ "Method", "called", "whenever", "the", "inner", "activity", "has", "been", "created", "or", "restarted", "and", "is", "ready", "to", "be", "used", "." ]
11cfa35a2eaa51f01f6678adb69bed0382a867e7
https://github.com/Karumi/Dexter/blob/11cfa35a2eaa51f01f6678adb69bed0382a867e7/dexter/src/main/java/com/karumi/dexter/DexterInstance.java#L106-L121
15,566
Karumi/Dexter
dexter/src/main/java/com/karumi/dexter/DexterInstance.java
DexterInstance.requestPermissionsToSystem
private void requestPermissionsToSystem(Collection<String> permissions) { if (!isShowingNativeDialog.get()) { androidPermissionService.requestPermissions(activity, permissions.toArray(new String[permissions.size()]), PERMISSIONS_REQUEST_CODE); } isShowingNativeDialog.set(true); }
java
private void requestPermissionsToSystem(Collection<String> permissions) { if (!isShowingNativeDialog.get()) { androidPermissionService.requestPermissions(activity, permissions.toArray(new String[permissions.size()]), PERMISSIONS_REQUEST_CODE); } isShowingNativeDialog.set(true); }
[ "private", "void", "requestPermissionsToSystem", "(", "Collection", "<", "String", ">", "permissions", ")", "{", "if", "(", "!", "isShowingNativeDialog", ".", "get", "(", ")", ")", "{", "androidPermissionService", ".", "requestPermissions", "(", "activity", ",", "permissions", ".", "toArray", "(", "new", "String", "[", "permissions", ".", "size", "(", ")", "]", ")", ",", "PERMISSIONS_REQUEST_CODE", ")", ";", "}", "isShowingNativeDialog", ".", "set", "(", "true", ")", ";", "}" ]
Starts the native request permissions process
[ "Starts", "the", "native", "request", "permissions", "process" ]
11cfa35a2eaa51f01f6678adb69bed0382a867e7
https://github.com/Karumi/Dexter/blob/11cfa35a2eaa51f01f6678adb69bed0382a867e7/dexter/src/main/java/com/karumi/dexter/DexterInstance.java#L166-L172
15,567
Karumi/Dexter
dexter/src/main/java/com/karumi/dexter/Dexter.java
Dexter.onPermissionsRequested
static void onPermissionsRequested(Collection<String> grantedPermissions, Collection<String> deniedPermissions) { /* Check against null values because sometimes the DexterActivity can call these internal methods when the DexterInstance has been cleaned up. Refer to this commit message for a more detailed explanation of the issue. */ if (instance != null) { instance.onPermissionRequestGranted(grantedPermissions); instance.onPermissionRequestDenied(deniedPermissions); } }
java
static void onPermissionsRequested(Collection<String> grantedPermissions, Collection<String> deniedPermissions) { /* Check against null values because sometimes the DexterActivity can call these internal methods when the DexterInstance has been cleaned up. Refer to this commit message for a more detailed explanation of the issue. */ if (instance != null) { instance.onPermissionRequestGranted(grantedPermissions); instance.onPermissionRequestDenied(deniedPermissions); } }
[ "static", "void", "onPermissionsRequested", "(", "Collection", "<", "String", ">", "grantedPermissions", ",", "Collection", "<", "String", ">", "deniedPermissions", ")", "{", "/* Check against null values because sometimes the DexterActivity can call these internal\n methods when the DexterInstance has been cleaned up.\n Refer to this commit message for a more detailed explanation of the issue.\n */", "if", "(", "instance", "!=", "null", ")", "{", "instance", ".", "onPermissionRequestGranted", "(", "grantedPermissions", ")", ";", "instance", ".", "onPermissionRequestDenied", "(", "deniedPermissions", ")", ";", "}", "}" ]
Method called when all the permissions has been requested to the user @param grantedPermissions Collection with all the permissions the user has granted. Contains values from {@link android.Manifest.permission} @param deniedPermissions Collection with all the permissions the user has denied. Contains values from {@link android.Manifest.permission}
[ "Method", "called", "when", "all", "the", "permissions", "has", "been", "requested", "to", "the", "user" ]
11cfa35a2eaa51f01f6678adb69bed0382a867e7
https://github.com/Karumi/Dexter/blob/11cfa35a2eaa51f01f6678adb69bed0382a867e7/dexter/src/main/java/com/karumi/dexter/Dexter.java#L162-L172
15,568
junit-team/junit4
src/main/java/org/junit/rules/TemporaryFolder.java
TemporaryFolder.newFile
public File newFile(String fileName) throws IOException { File file = new File(getRoot(), fileName); if (!file.createNewFile()) { throw new IOException( "a file with the name \'" + fileName + "\' already exists in the test folder"); } return file; }
java
public File newFile(String fileName) throws IOException { File file = new File(getRoot(), fileName); if (!file.createNewFile()) { throw new IOException( "a file with the name \'" + fileName + "\' already exists in the test folder"); } return file; }
[ "public", "File", "newFile", "(", "String", "fileName", ")", "throws", "IOException", "{", "File", "file", "=", "new", "File", "(", "getRoot", "(", ")", ",", "fileName", ")", ";", "if", "(", "!", "file", ".", "createNewFile", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"a file with the name \\'\"", "+", "fileName", "+", "\"\\' already exists in the test folder\"", ")", ";", "}", "return", "file", ";", "}" ]
Returns a new fresh file with the given name under the temporary folder.
[ "Returns", "a", "new", "fresh", "file", "with", "the", "given", "name", "under", "the", "temporary", "folder", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/rules/TemporaryFolder.java#L153-L160
15,569
junit-team/junit4
src/main/java/org/junit/runner/notification/RunNotifier.java
RunNotifier.addFirstListener
public void addFirstListener(RunListener listener) { if (listener == null) { throw new NullPointerException("Cannot add a null listener"); } listeners.add(0, wrapIfNotThreadSafe(listener)); }
java
public void addFirstListener(RunListener listener) { if (listener == null) { throw new NullPointerException("Cannot add a null listener"); } listeners.add(0, wrapIfNotThreadSafe(listener)); }
[ "public", "void", "addFirstListener", "(", "RunListener", "listener", ")", "{", "if", "(", "listener", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Cannot add a null listener\"", ")", ";", "}", "listeners", ".", "add", "(", "0", ",", "wrapIfNotThreadSafe", "(", "listener", ")", ")", ";", "}" ]
Internal use only. The Result's listener must be first.
[ "Internal", "use", "only", ".", "The", "Result", "s", "listener", "must", "be", "first", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runner/notification/RunNotifier.java#L243-L248
15,570
junit-team/junit4
src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java
FailOnTimeout.getThreadsInGroup
private List<Thread> getThreadsInGroup(ThreadGroup group) { final int activeThreadCount = group.activeCount(); // this is just an estimate int threadArraySize = Math.max(activeThreadCount * 2, 100); for (int loopCount = 0; loopCount < 5; loopCount++) { Thread[] threads = new Thread[threadArraySize]; int enumCount = group.enumerate(threads); if (enumCount < threadArraySize) { return Arrays.asList(threads).subList(0, enumCount); } // if there are too many threads to fit into the array, enumerate's result // is >= the array's length; therefore we can't trust that it returned all // the threads. Try again. threadArraySize += 100; } // threads are proliferating too fast for us. Bail before we get into // trouble. return Collections.emptyList(); }
java
private List<Thread> getThreadsInGroup(ThreadGroup group) { final int activeThreadCount = group.activeCount(); // this is just an estimate int threadArraySize = Math.max(activeThreadCount * 2, 100); for (int loopCount = 0; loopCount < 5; loopCount++) { Thread[] threads = new Thread[threadArraySize]; int enumCount = group.enumerate(threads); if (enumCount < threadArraySize) { return Arrays.asList(threads).subList(0, enumCount); } // if there are too many threads to fit into the array, enumerate's result // is >= the array's length; therefore we can't trust that it returned all // the threads. Try again. threadArraySize += 100; } // threads are proliferating too fast for us. Bail before we get into // trouble. return Collections.emptyList(); }
[ "private", "List", "<", "Thread", ">", "getThreadsInGroup", "(", "ThreadGroup", "group", ")", "{", "final", "int", "activeThreadCount", "=", "group", ".", "activeCount", "(", ")", ";", "// this is just an estimate", "int", "threadArraySize", "=", "Math", ".", "max", "(", "activeThreadCount", "*", "2", ",", "100", ")", ";", "for", "(", "int", "loopCount", "=", "0", ";", "loopCount", "<", "5", ";", "loopCount", "++", ")", "{", "Thread", "[", "]", "threads", "=", "new", "Thread", "[", "threadArraySize", "]", ";", "int", "enumCount", "=", "group", ".", "enumerate", "(", "threads", ")", ";", "if", "(", "enumCount", "<", "threadArraySize", ")", "{", "return", "Arrays", ".", "asList", "(", "threads", ")", ".", "subList", "(", "0", ",", "enumCount", ")", ";", "}", "// if there are too many threads to fit into the array, enumerate's result", "// is >= the array's length; therefore we can't trust that it returned all", "// the threads. Try again.", "threadArraySize", "+=", "100", ";", "}", "// threads are proliferating too fast for us. Bail before we get into ", "// trouble.", "return", "Collections", ".", "emptyList", "(", ")", ";", "}" ]
Returns all active threads belonging to a thread group. @param group The thread group. @return The active threads in the thread group. The result should be a complete list of the active threads at some point in time. Returns an empty list if this cannot be determined, e.g. because new threads are being created at an extremely fast rate.
[ "Returns", "all", "active", "threads", "belonging", "to", "a", "thread", "group", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java#L247-L264
15,571
junit-team/junit4
src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java
FailOnTimeout.cpuTime
private long cpuTime(Thread thr) { ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); if (mxBean.isThreadCpuTimeSupported()) { try { return mxBean.getThreadCpuTime(thr.getId()); } catch (UnsupportedOperationException e) { } } return 0; }
java
private long cpuTime(Thread thr) { ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); if (mxBean.isThreadCpuTimeSupported()) { try { return mxBean.getThreadCpuTime(thr.getId()); } catch (UnsupportedOperationException e) { } } return 0; }
[ "private", "long", "cpuTime", "(", "Thread", "thr", ")", "{", "ThreadMXBean", "mxBean", "=", "ManagementFactory", ".", "getThreadMXBean", "(", ")", ";", "if", "(", "mxBean", ".", "isThreadCpuTimeSupported", "(", ")", ")", "{", "try", "{", "return", "mxBean", ".", "getThreadCpuTime", "(", "thr", ".", "getId", "(", ")", ")", ";", "}", "catch", "(", "UnsupportedOperationException", "e", ")", "{", "}", "}", "return", "0", ";", "}" ]
Returns the CPU time used by a thread, if possible. @param thr The thread to query. @return The CPU time used by {@code thr}, or 0 if it cannot be determined.
[ "Returns", "the", "CPU", "time", "used", "by", "a", "thread", "if", "possible", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java#L271-L280
15,572
junit-team/junit4
src/main/java/org/junit/runner/JUnitCommandLineParseResult.java
JUnitCommandLineParseResult.parse
public static JUnitCommandLineParseResult parse(String[] args) { JUnitCommandLineParseResult result = new JUnitCommandLineParseResult(); result.parseArgs(args); return result; }
java
public static JUnitCommandLineParseResult parse(String[] args) { JUnitCommandLineParseResult result = new JUnitCommandLineParseResult(); result.parseArgs(args); return result; }
[ "public", "static", "JUnitCommandLineParseResult", "parse", "(", "String", "[", "]", "args", ")", "{", "JUnitCommandLineParseResult", "result", "=", "new", "JUnitCommandLineParseResult", "(", ")", ";", "result", ".", "parseArgs", "(", "args", ")", ";", "return", "result", ";", "}" ]
Parses the arguments. @param args Arguments
[ "Parses", "the", "arguments", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runner/JUnitCommandLineParseResult.java#L41-L47
15,573
junit-team/junit4
src/main/java/org/junit/experimental/results/ResultMatchers.java
ResultMatchers.hasSingleFailureMatching
public static Matcher<PrintableResult> hasSingleFailureMatching(final Matcher<Throwable> matcher) { return new TypeSafeMatcher<PrintableResult>() { @Override public boolean matchesSafely(PrintableResult item) { return item.failureCount() == 1 && matcher.matches(item.failures().get(0).getException()); } public void describeTo(Description description) { description.appendText("has failure with exception matching "); matcher.describeTo(description); } }; }
java
public static Matcher<PrintableResult> hasSingleFailureMatching(final Matcher<Throwable> matcher) { return new TypeSafeMatcher<PrintableResult>() { @Override public boolean matchesSafely(PrintableResult item) { return item.failureCount() == 1 && matcher.matches(item.failures().get(0).getException()); } public void describeTo(Description description) { description.appendText("has failure with exception matching "); matcher.describeTo(description); } }; }
[ "public", "static", "Matcher", "<", "PrintableResult", ">", "hasSingleFailureMatching", "(", "final", "Matcher", "<", "Throwable", ">", "matcher", ")", "{", "return", "new", "TypeSafeMatcher", "<", "PrintableResult", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matchesSafely", "(", "PrintableResult", "item", ")", "{", "return", "item", ".", "failureCount", "(", ")", "==", "1", "&&", "matcher", ".", "matches", "(", "item", ".", "failures", "(", ")", ".", "get", "(", "0", ")", ".", "getException", "(", ")", ")", ";", "}", "public", "void", "describeTo", "(", "Description", "description", ")", "{", "description", ".", "appendText", "(", "\"has failure with exception matching \"", ")", ";", "matcher", ".", "describeTo", "(", "description", ")", ";", "}", "}", ";", "}" ]
Matches if the result has exactly one failure matching the given matcher. @since 4.13
[ "Matches", "if", "the", "result", "has", "exactly", "one", "failure", "matching", "the", "given", "matcher", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/experimental/results/ResultMatchers.java#L70-L82
15,574
junit-team/junit4
src/main/java/org/junit/runners/model/RunnerBuilder.java
RunnerBuilder.safeRunnerForClass
public Runner safeRunnerForClass(Class<?> testClass) { try { Runner runner = runnerForClass(testClass); if (runner != null) { configureRunner(runner); } return runner; } catch (Throwable e) { return new ErrorReportingRunner(testClass, e); } }
java
public Runner safeRunnerForClass(Class<?> testClass) { try { Runner runner = runnerForClass(testClass); if (runner != null) { configureRunner(runner); } return runner; } catch (Throwable e) { return new ErrorReportingRunner(testClass, e); } }
[ "public", "Runner", "safeRunnerForClass", "(", "Class", "<", "?", ">", "testClass", ")", "{", "try", "{", "Runner", "runner", "=", "runnerForClass", "(", "testClass", ")", ";", "if", "(", "runner", "!=", "null", ")", "{", "configureRunner", "(", "runner", ")", ";", "}", "return", "runner", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "return", "new", "ErrorReportingRunner", "(", "testClass", ",", "e", ")", ";", "}", "}" ]
Always returns a runner for the given test class. <p>In case of an exception a runner will be returned that prints an error instead of running tests. <p>Note that some of the internal JUnit implementations of RunnerBuilder will return {@code null} from this method, but no RunnerBuilder passed to a Runner constructor will return {@code null} from this method. @param testClass class to be run @return a Runner
[ "Always", "returns", "a", "runner", "for", "the", "given", "test", "class", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runners/model/RunnerBuilder.java#L68-L78
15,575
junit-team/junit4
src/main/java/junit/framework/Assert.java
Assert.assertEquals
static public void assertEquals(String message, String expected, String actual) { if (expected == null && actual == null) { return; } if (expected != null && expected.equals(actual)) { return; } String cleanMessage = message == null ? "" : message; throw new ComparisonFailure(cleanMessage, expected, actual); }
java
static public void assertEquals(String message, String expected, String actual) { if (expected == null && actual == null) { return; } if (expected != null && expected.equals(actual)) { return; } String cleanMessage = message == null ? "" : message; throw new ComparisonFailure(cleanMessage, expected, actual); }
[ "static", "public", "void", "assertEquals", "(", "String", "message", ",", "String", "expected", ",", "String", "actual", ")", "{", "if", "(", "expected", "==", "null", "&&", "actual", "==", "null", ")", "{", "return", ";", "}", "if", "(", "expected", "!=", "null", "&&", "expected", ".", "equals", "(", "actual", ")", ")", "{", "return", ";", "}", "String", "cleanMessage", "=", "message", "==", "null", "?", "\"\"", ":", "message", ";", "throw", "new", "ComparisonFailure", "(", "cleanMessage", ",", "expected", ",", "actual", ")", ";", "}" ]
Asserts that two Strings are equal.
[ "Asserts", "that", "two", "Strings", "are", "equal", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/junit/framework/Assert.java#L92-L101
15,576
junit-team/junit4
src/main/java/junit/framework/Assert.java
Assert.assertEquals
static public void assertEquals(String message, long expected, long actual) { assertEquals(message, Long.valueOf(expected), Long.valueOf(actual)); }
java
static public void assertEquals(String message, long expected, long actual) { assertEquals(message, Long.valueOf(expected), Long.valueOf(actual)); }
[ "static", "public", "void", "assertEquals", "(", "String", "message", ",", "long", "expected", ",", "long", "actual", ")", "{", "assertEquals", "(", "message", ",", "Long", ".", "valueOf", "(", "expected", ")", ",", "Long", ".", "valueOf", "(", "actual", ")", ")", ";", "}" ]
Asserts that two longs are equal. If they are not an AssertionFailedError is thrown with the given message.
[ "Asserts", "that", "two", "longs", "are", "equal", ".", "If", "they", "are", "not", "an", "AssertionFailedError", "is", "thrown", "with", "the", "given", "message", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/junit/framework/Assert.java#L158-L160
15,577
junit-team/junit4
src/main/java/junit/framework/Assert.java
Assert.assertEquals
static public void assertEquals(String message, boolean expected, boolean actual) { assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual)); }
java
static public void assertEquals(String message, boolean expected, boolean actual) { assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual)); }
[ "static", "public", "void", "assertEquals", "(", "String", "message", ",", "boolean", "expected", ",", "boolean", "actual", ")", "{", "assertEquals", "(", "message", ",", "Boolean", ".", "valueOf", "(", "expected", ")", ",", "Boolean", ".", "valueOf", "(", "actual", ")", ")", ";", "}" ]
Asserts that two booleans are equal. If they are not an AssertionFailedError is thrown with the given message.
[ "Asserts", "that", "two", "booleans", "are", "equal", ".", "If", "they", "are", "not", "an", "AssertionFailedError", "is", "thrown", "with", "the", "given", "message", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/junit/framework/Assert.java#L173-L175
15,578
junit-team/junit4
src/main/java/junit/framework/Assert.java
Assert.assertEquals
static public void assertEquals(String message, byte expected, byte actual) { assertEquals(message, Byte.valueOf(expected), Byte.valueOf(actual)); }
java
static public void assertEquals(String message, byte expected, byte actual) { assertEquals(message, Byte.valueOf(expected), Byte.valueOf(actual)); }
[ "static", "public", "void", "assertEquals", "(", "String", "message", ",", "byte", "expected", ",", "byte", "actual", ")", "{", "assertEquals", "(", "message", ",", "Byte", ".", "valueOf", "(", "expected", ")", ",", "Byte", ".", "valueOf", "(", "actual", ")", ")", ";", "}" ]
Asserts that two bytes are equal. If they are not an AssertionFailedError is thrown with the given message.
[ "Asserts", "that", "two", "bytes", "are", "equal", ".", "If", "they", "are", "not", "an", "AssertionFailedError", "is", "thrown", "with", "the", "given", "message", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/junit/framework/Assert.java#L188-L190
15,579
junit-team/junit4
src/main/java/junit/framework/Assert.java
Assert.assertEquals
static public void assertEquals(String message, int expected, int actual) { assertEquals(message, Integer.valueOf(expected), Integer.valueOf(actual)); }
java
static public void assertEquals(String message, int expected, int actual) { assertEquals(message, Integer.valueOf(expected), Integer.valueOf(actual)); }
[ "static", "public", "void", "assertEquals", "(", "String", "message", ",", "int", "expected", ",", "int", "actual", ")", "{", "assertEquals", "(", "message", ",", "Integer", ".", "valueOf", "(", "expected", ")", ",", "Integer", ".", "valueOf", "(", "actual", ")", ")", ";", "}" ]
Asserts that two ints are equal. If they are not an AssertionFailedError is thrown with the given message.
[ "Asserts", "that", "two", "ints", "are", "equal", ".", "If", "they", "are", "not", "an", "AssertionFailedError", "is", "thrown", "with", "the", "given", "message", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/junit/framework/Assert.java#L233-L235
15,580
junit-team/junit4
src/main/java/junit/framework/Assert.java
Assert.assertNotSame
static public void assertNotSame(String message, Object expected, Object actual) { if (expected == actual) { failSame(message); } }
java
static public void assertNotSame(String message, Object expected, Object actual) { if (expected == actual) { failSame(message); } }
[ "static", "public", "void", "assertNotSame", "(", "String", "message", ",", "Object", "expected", ",", "Object", "actual", ")", "{", "if", "(", "expected", "==", "actual", ")", "{", "failSame", "(", "message", ")", ";", "}", "}" ]
Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown with the given message.
[ "Asserts", "that", "two", "objects", "do", "not", "refer", "to", "the", "same", "object", ".", "If", "they", "do", "refer", "to", "the", "same", "object", "an", "AssertionFailedError", "is", "thrown", "with", "the", "given", "message", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/junit/framework/Assert.java#L304-L308
15,581
junit-team/junit4
src/main/java/org/junit/runner/manipulation/Orderer.java
Orderer.order
public List<Description> order(Collection<Description> descriptions) throws InvalidOrderingException { List<Description> inOrder = ordering.orderItems( Collections.unmodifiableCollection(descriptions)); if (!ordering.validateOrderingIsCorrect()) { return inOrder; } Set<Description> uniqueDescriptions = new HashSet<Description>(descriptions); if (!uniqueDescriptions.containsAll(inOrder)) { throw new InvalidOrderingException("Ordering added items"); } Set<Description> resultAsSet = new HashSet<Description>(inOrder); if (resultAsSet.size() != inOrder.size()) { throw new InvalidOrderingException("Ordering duplicated items"); } else if (!resultAsSet.containsAll(uniqueDescriptions)) { throw new InvalidOrderingException("Ordering removed items"); } return inOrder; }
java
public List<Description> order(Collection<Description> descriptions) throws InvalidOrderingException { List<Description> inOrder = ordering.orderItems( Collections.unmodifiableCollection(descriptions)); if (!ordering.validateOrderingIsCorrect()) { return inOrder; } Set<Description> uniqueDescriptions = new HashSet<Description>(descriptions); if (!uniqueDescriptions.containsAll(inOrder)) { throw new InvalidOrderingException("Ordering added items"); } Set<Description> resultAsSet = new HashSet<Description>(inOrder); if (resultAsSet.size() != inOrder.size()) { throw new InvalidOrderingException("Ordering duplicated items"); } else if (!resultAsSet.containsAll(uniqueDescriptions)) { throw new InvalidOrderingException("Ordering removed items"); } return inOrder; }
[ "public", "List", "<", "Description", ">", "order", "(", "Collection", "<", "Description", ">", "descriptions", ")", "throws", "InvalidOrderingException", "{", "List", "<", "Description", ">", "inOrder", "=", "ordering", ".", "orderItems", "(", "Collections", ".", "unmodifiableCollection", "(", "descriptions", ")", ")", ";", "if", "(", "!", "ordering", ".", "validateOrderingIsCorrect", "(", ")", ")", "{", "return", "inOrder", ";", "}", "Set", "<", "Description", ">", "uniqueDescriptions", "=", "new", "HashSet", "<", "Description", ">", "(", "descriptions", ")", ";", "if", "(", "!", "uniqueDescriptions", ".", "containsAll", "(", "inOrder", ")", ")", "{", "throw", "new", "InvalidOrderingException", "(", "\"Ordering added items\"", ")", ";", "}", "Set", "<", "Description", ">", "resultAsSet", "=", "new", "HashSet", "<", "Description", ">", "(", "inOrder", ")", ";", "if", "(", "resultAsSet", ".", "size", "(", ")", "!=", "inOrder", ".", "size", "(", ")", ")", "{", "throw", "new", "InvalidOrderingException", "(", "\"Ordering duplicated items\"", ")", ";", "}", "else", "if", "(", "!", "resultAsSet", ".", "containsAll", "(", "uniqueDescriptions", ")", ")", "{", "throw", "new", "InvalidOrderingException", "(", "\"Ordering removed items\"", ")", ";", "}", "return", "inOrder", ";", "}" ]
Orders the descriptions. @return descriptions in order
[ "Orders", "the", "descriptions", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runner/manipulation/Orderer.java#L28-L48
15,582
junit-team/junit4
src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java
JUnit38ClassRunner.getAnnotations
private static Annotation[] getAnnotations(TestCase test) { try { Method m = test.getClass().getMethod(test.getName()); return m.getDeclaredAnnotations(); } catch (SecurityException e) { } catch (NoSuchMethodException e) { } return new Annotation[0]; }
java
private static Annotation[] getAnnotations(TestCase test) { try { Method m = test.getClass().getMethod(test.getName()); return m.getDeclaredAnnotations(); } catch (SecurityException e) { } catch (NoSuchMethodException e) { } return new Annotation[0]; }
[ "private", "static", "Annotation", "[", "]", "getAnnotations", "(", "TestCase", "test", ")", "{", "try", "{", "Method", "m", "=", "test", ".", "getClass", "(", ")", ".", "getMethod", "(", "test", ".", "getName", "(", ")", ")", ";", "return", "m", ".", "getDeclaredAnnotations", "(", ")", ";", "}", "catch", "(", "SecurityException", "e", ")", "{", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "}", "return", "new", "Annotation", "[", "0", "]", ";", "}" ]
Get the annotations associated with given TestCase. @param test the TestCase.
[ "Get", "the", "annotations", "associated", "with", "given", "TestCase", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java#L133-L141
15,583
junit-team/junit4
src/main/java/org/junit/rules/ErrorCollector.java
ErrorCollector.addError
public void addError(Throwable error) { if (error == null) { throw new NullPointerException("Error cannot be null"); } if (error instanceof AssumptionViolatedException) { AssertionError e = new AssertionError(error.getMessage()); e.initCause(error); errors.add(e); } else { errors.add(error); } }
java
public void addError(Throwable error) { if (error == null) { throw new NullPointerException("Error cannot be null"); } if (error instanceof AssumptionViolatedException) { AssertionError e = new AssertionError(error.getMessage()); e.initCause(error); errors.add(e); } else { errors.add(error); } }
[ "public", "void", "addError", "(", "Throwable", "error", ")", "{", "if", "(", "error", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Error cannot be null\"", ")", ";", "}", "if", "(", "error", "instanceof", "AssumptionViolatedException", ")", "{", "AssertionError", "e", "=", "new", "AssertionError", "(", "error", ".", "getMessage", "(", ")", ")", ";", "e", ".", "initCause", "(", "error", ")", ";", "errors", ".", "add", "(", "e", ")", ";", "}", "else", "{", "errors", ".", "add", "(", "error", ")", ";", "}", "}" ]
Adds a Throwable to the table. Execution continues, but the test will fail at the end.
[ "Adds", "a", "Throwable", "to", "the", "table", ".", "Execution", "continues", "but", "the", "test", "will", "fail", "at", "the", "end", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/rules/ErrorCollector.java#L48-L59
15,584
junit-team/junit4
src/main/java/org/junit/internal/Throwables.java
Throwables.getTrimmedStackTrace
public static String getTrimmedStackTrace(Throwable exception) { List<String> trimmedStackTraceLines = getTrimmedStackTraceLines(exception); if (trimmedStackTraceLines.isEmpty()) { return getFullStackTrace(exception); } StringBuilder result = new StringBuilder(exception.toString()); appendStackTraceLines(trimmedStackTraceLines, result); appendStackTraceLines(getCauseStackTraceLines(exception), result); return result.toString(); }
java
public static String getTrimmedStackTrace(Throwable exception) { List<String> trimmedStackTraceLines = getTrimmedStackTraceLines(exception); if (trimmedStackTraceLines.isEmpty()) { return getFullStackTrace(exception); } StringBuilder result = new StringBuilder(exception.toString()); appendStackTraceLines(trimmedStackTraceLines, result); appendStackTraceLines(getCauseStackTraceLines(exception), result); return result.toString(); }
[ "public", "static", "String", "getTrimmedStackTrace", "(", "Throwable", "exception", ")", "{", "List", "<", "String", ">", "trimmedStackTraceLines", "=", "getTrimmedStackTraceLines", "(", "exception", ")", ";", "if", "(", "trimmedStackTraceLines", ".", "isEmpty", "(", ")", ")", "{", "return", "getFullStackTrace", "(", "exception", ")", ";", "}", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "exception", ".", "toString", "(", ")", ")", ";", "appendStackTraceLines", "(", "trimmedStackTraceLines", ",", "result", ")", ";", "appendStackTraceLines", "(", "getCauseStackTraceLines", "(", "exception", ")", ",", "result", ")", ";", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Gets a trimmed version of the stack trace of the given exception. Stack trace elements that are below the test method are filtered out. @return a trimmed stack trace, or the original trace if trimming wasn't possible
[ "Gets", "a", "trimmed", "version", "of", "the", "stack", "trace", "of", "the", "given", "exception", ".", "Stack", "trace", "elements", "that", "are", "below", "the", "test", "method", "are", "filtered", "out", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/internal/Throwables.java#L73-L83
15,585
junit-team/junit4
src/main/java/org/junit/runners/RuleContainer.java
RuleContainer.getSortedEntries
private List<RuleEntry> getSortedEntries() { List<RuleEntry> ruleEntries = new ArrayList<RuleEntry>( methodRules.size() + testRules.size()); for (MethodRule rule : methodRules) { ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_METHOD_RULE, orderValues.get(rule))); } for (TestRule rule : testRules) { ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_TEST_RULE, orderValues.get(rule))); } Collections.sort(ruleEntries, ENTRY_COMPARATOR); return ruleEntries; }
java
private List<RuleEntry> getSortedEntries() { List<RuleEntry> ruleEntries = new ArrayList<RuleEntry>( methodRules.size() + testRules.size()); for (MethodRule rule : methodRules) { ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_METHOD_RULE, orderValues.get(rule))); } for (TestRule rule : testRules) { ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_TEST_RULE, orderValues.get(rule))); } Collections.sort(ruleEntries, ENTRY_COMPARATOR); return ruleEntries; }
[ "private", "List", "<", "RuleEntry", ">", "getSortedEntries", "(", ")", "{", "List", "<", "RuleEntry", ">", "ruleEntries", "=", "new", "ArrayList", "<", "RuleEntry", ">", "(", "methodRules", ".", "size", "(", ")", "+", "testRules", ".", "size", "(", ")", ")", ";", "for", "(", "MethodRule", "rule", ":", "methodRules", ")", "{", "ruleEntries", ".", "add", "(", "new", "RuleEntry", "(", "rule", ",", "RuleEntry", ".", "TYPE_METHOD_RULE", ",", "orderValues", ".", "get", "(", "rule", ")", ")", ")", ";", "}", "for", "(", "TestRule", "rule", ":", "testRules", ")", "{", "ruleEntries", ".", "add", "(", "new", "RuleEntry", "(", "rule", ",", "RuleEntry", ".", "TYPE_TEST_RULE", ",", "orderValues", ".", "get", "(", "rule", ")", ")", ")", ";", "}", "Collections", ".", "sort", "(", "ruleEntries", ",", "ENTRY_COMPARATOR", ")", ";", "return", "ruleEntries", ";", "}" ]
Returns entries in the order how they should be applied, i.e. inner-to-outer.
[ "Returns", "entries", "in", "the", "order", "how", "they", "should", "be", "applied", "i", ".", "e", ".", "inner", "-", "to", "-", "outer", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runners/RuleContainer.java#L55-L66
15,586
junit-team/junit4
src/main/java/org/junit/runners/RuleContainer.java
RuleContainer.getSortedRules
List<Object> getSortedRules() { List<Object> result = new ArrayList<Object>(); for (RuleEntry entry : getSortedEntries()) { result.add(entry.rule); } return result; }
java
List<Object> getSortedRules() { List<Object> result = new ArrayList<Object>(); for (RuleEntry entry : getSortedEntries()) { result.add(entry.rule); } return result; }
[ "List", "<", "Object", ">", "getSortedRules", "(", ")", "{", "List", "<", "Object", ">", "result", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ";", "for", "(", "RuleEntry", "entry", ":", "getSortedEntries", "(", ")", ")", "{", "result", ".", "add", "(", "entry", ".", "rule", ")", ";", "}", "return", "result", ";", "}" ]
Returns rule instances in the order how they should be applied, i.e. inner-to-outer. VisibleForTesting
[ "Returns", "rule", "instances", "in", "the", "order", "how", "they", "should", "be", "applied", "i", ".", "e", ".", "inner", "-", "to", "-", "outer", ".", "VisibleForTesting" ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runners/RuleContainer.java#L91-L97
15,587
junit-team/junit4
src/main/java/org/junit/runner/JUnitCore.java
JUnitCore.run
public Result run(Runner runner) { Result result = new Result(); RunListener listener = result.createListener(); notifier.addFirstListener(listener); try { notifier.fireTestRunStarted(runner.getDescription()); runner.run(notifier); notifier.fireTestRunFinished(result); } finally { removeListener(listener); } return result; }
java
public Result run(Runner runner) { Result result = new Result(); RunListener listener = result.createListener(); notifier.addFirstListener(listener); try { notifier.fireTestRunStarted(runner.getDescription()); runner.run(notifier); notifier.fireTestRunFinished(result); } finally { removeListener(listener); } return result; }
[ "public", "Result", "run", "(", "Runner", "runner", ")", "{", "Result", "result", "=", "new", "Result", "(", ")", ";", "RunListener", "listener", "=", "result", ".", "createListener", "(", ")", ";", "notifier", ".", "addFirstListener", "(", "listener", ")", ";", "try", "{", "notifier", ".", "fireTestRunStarted", "(", "runner", ".", "getDescription", "(", ")", ")", ";", "runner", ".", "run", "(", "notifier", ")", ";", "notifier", ".", "fireTestRunFinished", "(", "result", ")", ";", "}", "finally", "{", "removeListener", "(", "listener", ")", ";", "}", "return", "result", ";", "}" ]
Do not use. Testing purposes only.
[ "Do", "not", "use", ".", "Testing", "purposes", "only", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runner/JUnitCore.java#L131-L143
15,588
junit-team/junit4
src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java
ThrowableCauseMatcher.hasCause
@Factory public static <T extends Throwable> Matcher<T> hasCause(final Matcher<?> matcher) { return new ThrowableCauseMatcher<T>(matcher); }
java
@Factory public static <T extends Throwable> Matcher<T> hasCause(final Matcher<?> matcher) { return new ThrowableCauseMatcher<T>(matcher); }
[ "@", "Factory", "public", "static", "<", "T", "extends", "Throwable", ">", "Matcher", "<", "T", ">", "hasCause", "(", "final", "Matcher", "<", "?", ">", "matcher", ")", "{", "return", "new", "ThrowableCauseMatcher", "<", "T", ">", "(", "matcher", ")", ";", "}" ]
Returns a matcher that verifies that the outer exception has a cause for which the supplied matcher evaluates to true. @param matcher to apply to the cause of the outer exception @param <T> type of the outer exception
[ "Returns", "a", "matcher", "that", "verifies", "that", "the", "outer", "exception", "has", "a", "cause", "for", "which", "the", "supplied", "matcher", "evaluates", "to", "true", "." ]
d9861ecdb6e487f6c352437ee823879aca3b81d4
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java#L48-L51
15,589
knowm/XChange
xchange-paymium/src/main/java/org/knowm/xchange/paymium/PaymiumAdapters.java
PaymiumAdapters.adaptTicker
public static Ticker adaptTicker(PaymiumTicker PaymiumTicker, CurrencyPair currencyPair) { BigDecimal bid = PaymiumTicker.getBid(); BigDecimal ask = PaymiumTicker.getAsk(); BigDecimal high = PaymiumTicker.getHigh(); BigDecimal low = PaymiumTicker.getLow(); BigDecimal last = PaymiumTicker.getPrice(); BigDecimal volume = PaymiumTicker.getVolume(); Date timestamp = new Date(PaymiumTicker.getAt() * 1000L); return new Ticker.Builder() .currencyPair(currencyPair) .bid(bid) .ask(ask) .high(high) .low(low) .last(last) .volume(volume) .timestamp(timestamp) .build(); }
java
public static Ticker adaptTicker(PaymiumTicker PaymiumTicker, CurrencyPair currencyPair) { BigDecimal bid = PaymiumTicker.getBid(); BigDecimal ask = PaymiumTicker.getAsk(); BigDecimal high = PaymiumTicker.getHigh(); BigDecimal low = PaymiumTicker.getLow(); BigDecimal last = PaymiumTicker.getPrice(); BigDecimal volume = PaymiumTicker.getVolume(); Date timestamp = new Date(PaymiumTicker.getAt() * 1000L); return new Ticker.Builder() .currencyPair(currencyPair) .bid(bid) .ask(ask) .high(high) .low(low) .last(last) .volume(volume) .timestamp(timestamp) .build(); }
[ "public", "static", "Ticker", "adaptTicker", "(", "PaymiumTicker", "PaymiumTicker", ",", "CurrencyPair", "currencyPair", ")", "{", "BigDecimal", "bid", "=", "PaymiumTicker", ".", "getBid", "(", ")", ";", "BigDecimal", "ask", "=", "PaymiumTicker", ".", "getAsk", "(", ")", ";", "BigDecimal", "high", "=", "PaymiumTicker", ".", "getHigh", "(", ")", ";", "BigDecimal", "low", "=", "PaymiumTicker", ".", "getLow", "(", ")", ";", "BigDecimal", "last", "=", "PaymiumTicker", ".", "getPrice", "(", ")", ";", "BigDecimal", "volume", "=", "PaymiumTicker", ".", "getVolume", "(", ")", ";", "Date", "timestamp", "=", "new", "Date", "(", "PaymiumTicker", ".", "getAt", "(", ")", "*", "1000L", ")", ";", "return", "new", "Ticker", ".", "Builder", "(", ")", ".", "currencyPair", "(", "currencyPair", ")", ".", "bid", "(", "bid", ")", ".", "ask", "(", "ask", ")", ".", "high", "(", "high", ")", ".", "low", "(", "low", ")", ".", "last", "(", "last", ")", ".", "volume", "(", "volume", ")", ".", "timestamp", "(", "timestamp", ")", ".", "build", "(", ")", ";", "}" ]
Adapts a PaymiumTicker to a Ticker Object @param PaymiumTicker The exchange specific ticker @param currencyPair (e.g. BTC/USD) @return The ticker
[ "Adapts", "a", "PaymiumTicker", "to", "a", "Ticker", "Object" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-paymium/src/main/java/org/knowm/xchange/paymium/PaymiumAdapters.java#L36-L56
15,590
knowm/XChange
xchange-koinim/src/main/java/org/knowm/xchange/koinim/KoinimAdapters.java
KoinimAdapters.adaptTicker
public static Ticker adaptTicker(KoinimTicker koinimTicker, CurrencyPair currencyPair) { if (!currencyPair.equals(new CurrencyPair(BTC, TRY))) { throw new NotAvailableFromExchangeException(); } if (koinimTicker != null) { return new Ticker.Builder() .currencyPair(new CurrencyPair(BTC, Currency.TRY)) .last(koinimTicker.getSell()) .bid(koinimTicker.getBid()) .ask(koinimTicker.getAsk()) .high(koinimTicker.getHigh()) .low(koinimTicker.getLow()) .volume(koinimTicker.getVolume()) .vwap(koinimTicker.getAvg()) .build(); } return null; }
java
public static Ticker adaptTicker(KoinimTicker koinimTicker, CurrencyPair currencyPair) { if (!currencyPair.equals(new CurrencyPair(BTC, TRY))) { throw new NotAvailableFromExchangeException(); } if (koinimTicker != null) { return new Ticker.Builder() .currencyPair(new CurrencyPair(BTC, Currency.TRY)) .last(koinimTicker.getSell()) .bid(koinimTicker.getBid()) .ask(koinimTicker.getAsk()) .high(koinimTicker.getHigh()) .low(koinimTicker.getLow()) .volume(koinimTicker.getVolume()) .vwap(koinimTicker.getAvg()) .build(); } return null; }
[ "public", "static", "Ticker", "adaptTicker", "(", "KoinimTicker", "koinimTicker", ",", "CurrencyPair", "currencyPair", ")", "{", "if", "(", "!", "currencyPair", ".", "equals", "(", "new", "CurrencyPair", "(", "BTC", ",", "TRY", ")", ")", ")", "{", "throw", "new", "NotAvailableFromExchangeException", "(", ")", ";", "}", "if", "(", "koinimTicker", "!=", "null", ")", "{", "return", "new", "Ticker", ".", "Builder", "(", ")", ".", "currencyPair", "(", "new", "CurrencyPair", "(", "BTC", ",", "Currency", ".", "TRY", ")", ")", ".", "last", "(", "koinimTicker", ".", "getSell", "(", ")", ")", ".", "bid", "(", "koinimTicker", ".", "getBid", "(", ")", ")", ".", "ask", "(", "koinimTicker", ".", "getAsk", "(", ")", ")", ".", "high", "(", "koinimTicker", ".", "getHigh", "(", ")", ")", ".", "low", "(", "koinimTicker", ".", "getLow", "(", ")", ")", ".", "volume", "(", "koinimTicker", ".", "getVolume", "(", ")", ")", ".", "vwap", "(", "koinimTicker", ".", "getAvg", "(", ")", ")", ".", "build", "(", ")", ";", "}", "return", "null", ";", "}" ]
Adapts a KoinimTicker to a Ticker Object @param koinimTicker The exchange specific ticker @param currencyPair @return The ticker
[ "Adapts", "a", "KoinimTicker", "to", "a", "Ticker", "Object" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-koinim/src/main/java/org/knowm/xchange/koinim/KoinimAdapters.java#L24-L43
15,591
knowm/XChange
xchange-core/src/main/java/org/knowm/xchange/utils/CertHelper.java
CertHelper.trustAllCerts
@Deprecated public static void trustAllCerts() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); }
java
@Deprecated public static void trustAllCerts() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); }
[ "@", "Deprecated", "public", "static", "void", "trustAllCerts", "(", ")", "throws", "Exception", "{", "TrustManager", "[", "]", "trustAllCerts", "=", "new", "TrustManager", "[", "]", "{", "new", "X509TrustManager", "(", ")", "{", "@", "Override", "public", "java", ".", "security", ".", "cert", ".", "X509Certificate", "[", "]", "getAcceptedIssuers", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "void", "checkClientTrusted", "(", "X509Certificate", "[", "]", "certs", ",", "String", "authType", ")", "{", "}", "@", "Override", "public", "void", "checkServerTrusted", "(", "X509Certificate", "[", "]", "certs", ",", "String", "authType", ")", "{", "}", "}", "}", ";", "// Install the all-trusting trust manager", "SSLContext", "sc", "=", "SSLContext", ".", "getInstance", "(", "\"SSL\"", ")", ";", "sc", ".", "init", "(", "null", ",", "trustAllCerts", ",", "new", "java", ".", "security", ".", "SecureRandom", "(", ")", ")", ";", "HttpsURLConnection", ".", "setDefaultSSLSocketFactory", "(", "sc", ".", "getSocketFactory", "(", ")", ")", ";", "// Create all-trusting host name verifier", "HostnameVerifier", "allHostsValid", "=", "new", "HostnameVerifier", "(", ")", "{", "@", "Override", "public", "boolean", "verify", "(", "String", "hostname", ",", "SSLSession", "session", ")", "{", "return", "true", ";", "}", "}", ";", "// Install the all-trusting host verifier", "HttpsURLConnection", ".", "setDefaultHostnameVerifier", "(", "allHostsValid", ")", ";", "}" ]
Manually override the JVM's TrustManager to accept all HTTPS connections. Use this ONLY for testing, and even at that use it cautiously. Someone could steal your API keys with a MITM attack! @deprecated create an exclusion specific to your need rather than changing all behavior
[ "Manually", "override", "the", "JVM", "s", "TrustManager", "to", "accept", "all", "HTTPS", "connections", ".", "Use", "this", "ONLY", "for", "testing", "and", "even", "at", "that", "use", "it", "cautiously", ".", "Someone", "could", "steal", "your", "API", "keys", "with", "a", "MITM", "attack!" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-core/src/main/java/org/knowm/xchange/utils/CertHelper.java#L250-L289
15,592
knowm/XChange
xchange-core/src/main/java/org/knowm/xchange/dto/account/Wallet.java
Wallet.getBalance
public Balance getBalance(Currency currency) { Balance balance = this.balances.get(currency); return balance == null ? Balance.zero(currency) : balance; }
java
public Balance getBalance(Currency currency) { Balance balance = this.balances.get(currency); return balance == null ? Balance.zero(currency) : balance; }
[ "public", "Balance", "getBalance", "(", "Currency", "currency", ")", "{", "Balance", "balance", "=", "this", ".", "balances", ".", "get", "(", "currency", ")", ";", "return", "balance", "==", "null", "?", "Balance", ".", "zero", "(", "currency", ")", ":", "balance", ";", "}" ]
Returns the balance for the specified currency. @param currency a {@link Currency}. @return the balance of the specified currency, or a zero balance if currency not present
[ "Returns", "the", "balance", "for", "the", "specified", "currency", "." ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-core/src/main/java/org/knowm/xchange/dto/account/Wallet.java#L106-L110
15,593
knowm/XChange
xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java
CoinbaseProAdapters.adaptOrderStatus
public static OrderStatus adaptOrderStatus(CoinbaseProOrder order) { if (order.getStatus().equals("pending")) { return OrderStatus.PENDING_NEW; } if (order.getStatus().equals("done") || order.getStatus().equals("settled")) { if (order.getDoneReason().equals("filled")) { return OrderStatus.FILLED; } if (order.getDoneReason().equals("canceled")) { return OrderStatus.CANCELED; } return OrderStatus.UNKNOWN; } if (order.getFilledSize().signum() == 0) { if (order.getStatus().equals("open") && order.getStop() != null) { // This is a massive edge case of a stop triggering but not immediately // fulfilling. STOPPED status is only currently used by the HitBTC and // YoBit implementations and in both cases it looks like a // misunderstanding and those should return CANCELLED. Should we just // remove this status? return OrderStatus.STOPPED; } return OrderStatus.NEW; } if (order.getFilledSize().compareTo(BigDecimal.ZERO) > 0 // if size >= filledSize order should be partially filled && order.getSize().compareTo(order.getFilledSize()) >= 0) return OrderStatus.PARTIALLY_FILLED; return OrderStatus.UNKNOWN; }
java
public static OrderStatus adaptOrderStatus(CoinbaseProOrder order) { if (order.getStatus().equals("pending")) { return OrderStatus.PENDING_NEW; } if (order.getStatus().equals("done") || order.getStatus().equals("settled")) { if (order.getDoneReason().equals("filled")) { return OrderStatus.FILLED; } if (order.getDoneReason().equals("canceled")) { return OrderStatus.CANCELED; } return OrderStatus.UNKNOWN; } if (order.getFilledSize().signum() == 0) { if (order.getStatus().equals("open") && order.getStop() != null) { // This is a massive edge case of a stop triggering but not immediately // fulfilling. STOPPED status is only currently used by the HitBTC and // YoBit implementations and in both cases it looks like a // misunderstanding and those should return CANCELLED. Should we just // remove this status? return OrderStatus.STOPPED; } return OrderStatus.NEW; } if (order.getFilledSize().compareTo(BigDecimal.ZERO) > 0 // if size >= filledSize order should be partially filled && order.getSize().compareTo(order.getFilledSize()) >= 0) return OrderStatus.PARTIALLY_FILLED; return OrderStatus.UNKNOWN; }
[ "public", "static", "OrderStatus", "adaptOrderStatus", "(", "CoinbaseProOrder", "order", ")", "{", "if", "(", "order", ".", "getStatus", "(", ")", ".", "equals", "(", "\"pending\"", ")", ")", "{", "return", "OrderStatus", ".", "PENDING_NEW", ";", "}", "if", "(", "order", ".", "getStatus", "(", ")", ".", "equals", "(", "\"done\"", ")", "||", "order", ".", "getStatus", "(", ")", ".", "equals", "(", "\"settled\"", ")", ")", "{", "if", "(", "order", ".", "getDoneReason", "(", ")", ".", "equals", "(", "\"filled\"", ")", ")", "{", "return", "OrderStatus", ".", "FILLED", ";", "}", "if", "(", "order", ".", "getDoneReason", "(", ")", ".", "equals", "(", "\"canceled\"", ")", ")", "{", "return", "OrderStatus", ".", "CANCELED", ";", "}", "return", "OrderStatus", ".", "UNKNOWN", ";", "}", "if", "(", "order", ".", "getFilledSize", "(", ")", ".", "signum", "(", ")", "==", "0", ")", "{", "if", "(", "order", ".", "getStatus", "(", ")", ".", "equals", "(", "\"open\"", ")", "&&", "order", ".", "getStop", "(", ")", "!=", "null", ")", "{", "// This is a massive edge case of a stop triggering but not immediately", "// fulfilling. STOPPED status is only currently used by the HitBTC and", "// YoBit implementations and in both cases it looks like a", "// misunderstanding and those should return CANCELLED. Should we just", "// remove this status?", "return", "OrderStatus", ".", "STOPPED", ";", "}", "return", "OrderStatus", ".", "NEW", ";", "}", "if", "(", "order", ".", "getFilledSize", "(", ")", ".", "compareTo", "(", "BigDecimal", ".", "ZERO", ")", ">", "0", "// if size >= filledSize order should be partially filled", "&&", "order", ".", "getSize", "(", ")", ".", "compareTo", "(", "order", ".", "getFilledSize", "(", ")", ")", ">=", "0", ")", "return", "OrderStatus", ".", "PARTIALLY_FILLED", ";", "return", "OrderStatus", ".", "UNKNOWN", ";", "}" ]
The status from the CoinbaseProOrder object converted to xchange status
[ "The", "status", "from", "the", "CoinbaseProOrder", "object", "converted", "to", "xchange", "status" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java#L259-L298
15,594
knowm/XChange
xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java
CoinbaseProAdapters.adaptCoinbaseProStopOrder
public static CoinbaseProPlaceOrder adaptCoinbaseProStopOrder(StopOrder stopOrder) { // stop orders can also execute as 'stop limit' orders, that is converting to // a limit order, but a traditional 'stop' order converts to a market order if (stopOrder.getLimitPrice() == null) { return new CoinbaseProPlaceMarketOrder.Builder() .productId(adaptProductID(stopOrder.getCurrencyPair())) .type(CoinbaseProPlaceOrder.Type.market) .side(adaptSide(stopOrder.getType())) .size(stopOrder.getOriginalAmount()) .stop(adaptStop(stopOrder.getType())) .stopPrice(stopOrder.getStopPrice()) .build(); } return new CoinbaseProPlaceLimitOrder.Builder() .productId(adaptProductID(stopOrder.getCurrencyPair())) .type(CoinbaseProPlaceOrder.Type.limit) .side(adaptSide(stopOrder.getType())) .size(stopOrder.getOriginalAmount()) .stop(adaptStop(stopOrder.getType())) .stopPrice(stopOrder.getStopPrice()) .price(stopOrder.getLimitPrice()) .build(); }
java
public static CoinbaseProPlaceOrder adaptCoinbaseProStopOrder(StopOrder stopOrder) { // stop orders can also execute as 'stop limit' orders, that is converting to // a limit order, but a traditional 'stop' order converts to a market order if (stopOrder.getLimitPrice() == null) { return new CoinbaseProPlaceMarketOrder.Builder() .productId(adaptProductID(stopOrder.getCurrencyPair())) .type(CoinbaseProPlaceOrder.Type.market) .side(adaptSide(stopOrder.getType())) .size(stopOrder.getOriginalAmount()) .stop(adaptStop(stopOrder.getType())) .stopPrice(stopOrder.getStopPrice()) .build(); } return new CoinbaseProPlaceLimitOrder.Builder() .productId(adaptProductID(stopOrder.getCurrencyPair())) .type(CoinbaseProPlaceOrder.Type.limit) .side(adaptSide(stopOrder.getType())) .size(stopOrder.getOriginalAmount()) .stop(adaptStop(stopOrder.getType())) .stopPrice(stopOrder.getStopPrice()) .price(stopOrder.getLimitPrice()) .build(); }
[ "public", "static", "CoinbaseProPlaceOrder", "adaptCoinbaseProStopOrder", "(", "StopOrder", "stopOrder", ")", "{", "// stop orders can also execute as 'stop limit' orders, that is converting to", "// a limit order, but a traditional 'stop' order converts to a market order", "if", "(", "stopOrder", ".", "getLimitPrice", "(", ")", "==", "null", ")", "{", "return", "new", "CoinbaseProPlaceMarketOrder", ".", "Builder", "(", ")", ".", "productId", "(", "adaptProductID", "(", "stopOrder", ".", "getCurrencyPair", "(", ")", ")", ")", ".", "type", "(", "CoinbaseProPlaceOrder", ".", "Type", ".", "market", ")", ".", "side", "(", "adaptSide", "(", "stopOrder", ".", "getType", "(", ")", ")", ")", ".", "size", "(", "stopOrder", ".", "getOriginalAmount", "(", ")", ")", ".", "stop", "(", "adaptStop", "(", "stopOrder", ".", "getType", "(", ")", ")", ")", ".", "stopPrice", "(", "stopOrder", ".", "getStopPrice", "(", ")", ")", ".", "build", "(", ")", ";", "}", "return", "new", "CoinbaseProPlaceLimitOrder", ".", "Builder", "(", ")", ".", "productId", "(", "adaptProductID", "(", "stopOrder", ".", "getCurrencyPair", "(", ")", ")", ")", ".", "type", "(", "CoinbaseProPlaceOrder", ".", "Type", ".", "limit", ")", ".", "side", "(", "adaptSide", "(", "stopOrder", ".", "getType", "(", ")", ")", ")", ".", "size", "(", "stopOrder", ".", "getOriginalAmount", "(", ")", ")", ".", "stop", "(", "adaptStop", "(", "stopOrder", ".", "getType", "(", ")", ")", ")", ".", "stopPrice", "(", "stopOrder", ".", "getStopPrice", "(", ")", ")", ".", "price", "(", "stopOrder", ".", "getLimitPrice", "(", ")", ")", ".", "build", "(", ")", ";", "}" ]
Creates a 'stop' order. Stop limit order converts to a limit order when the stop amount is triggered. The limit order can have a different price than the stop price. <p>If the stop order has no limit price it will execute as a market order once the stop price is broken @param stopOrder @return
[ "Creates", "a", "stop", "order", ".", "Stop", "limit", "order", "converts", "to", "a", "limit", "order", "when", "the", "stop", "amount", "is", "triggered", ".", "The", "limit", "order", "can", "have", "a", "different", "price", "than", "the", "stop", "price", "." ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java#L457-L479
15,595
knowm/XChange
xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java
CexIOAdapters.adaptTrade
public static Trade adaptTrade(CexIOTrade trade, CurrencyPair currencyPair) { BigDecimal amount = trade.getAmount(); BigDecimal price = trade.getPrice(); Date date = DateUtils.fromMillisUtc(trade.getDate() * 1000L); OrderType type = trade.getType().equals(ORDER_TYPE_BUY) ? OrderType.BID : OrderType.ASK; return new Trade(type, amount, currencyPair, price, date, String.valueOf(trade.getTid())); }
java
public static Trade adaptTrade(CexIOTrade trade, CurrencyPair currencyPair) { BigDecimal amount = trade.getAmount(); BigDecimal price = trade.getPrice(); Date date = DateUtils.fromMillisUtc(trade.getDate() * 1000L); OrderType type = trade.getType().equals(ORDER_TYPE_BUY) ? OrderType.BID : OrderType.ASK; return new Trade(type, amount, currencyPair, price, date, String.valueOf(trade.getTid())); }
[ "public", "static", "Trade", "adaptTrade", "(", "CexIOTrade", "trade", ",", "CurrencyPair", "currencyPair", ")", "{", "BigDecimal", "amount", "=", "trade", ".", "getAmount", "(", ")", ";", "BigDecimal", "price", "=", "trade", ".", "getPrice", "(", ")", ";", "Date", "date", "=", "DateUtils", ".", "fromMillisUtc", "(", "trade", ".", "getDate", "(", ")", "*", "1000L", ")", ";", "OrderType", "type", "=", "trade", ".", "getType", "(", ")", ".", "equals", "(", "ORDER_TYPE_BUY", ")", "?", "OrderType", ".", "BID", ":", "OrderType", ".", "ASK", ";", "return", "new", "Trade", "(", "type", ",", "amount", ",", "currencyPair", ",", "price", ",", "date", ",", "String", ".", "valueOf", "(", "trade", ".", "getTid", "(", ")", ")", ")", ";", "}" ]
Adapts a CexIOTrade to a Trade Object @param trade CexIO trade object @param currencyPair trade currencies @return The XChange Trade
[ "Adapts", "a", "CexIOTrade", "to", "a", "Trade", "Object" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java#L46-L53
15,596
knowm/XChange
xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java
CexIOAdapters.adaptTicker
public static Ticker adaptTicker(CexIOTicker ticker) { if (ticker.getPair() == null) { throw new IllegalArgumentException("Missing currency pair in ticker: " + ticker); } return adaptTicker(ticker, adaptCurrencyPair(ticker.getPair())); }
java
public static Ticker adaptTicker(CexIOTicker ticker) { if (ticker.getPair() == null) { throw new IllegalArgumentException("Missing currency pair in ticker: " + ticker); } return adaptTicker(ticker, adaptCurrencyPair(ticker.getPair())); }
[ "public", "static", "Ticker", "adaptTicker", "(", "CexIOTicker", "ticker", ")", "{", "if", "(", "ticker", ".", "getPair", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Missing currency pair in ticker: \"", "+", "ticker", ")", ";", "}", "return", "adaptTicker", "(", "ticker", ",", "adaptCurrencyPair", "(", "ticker", ".", "getPair", "(", ")", ")", ")", ";", "}" ]
Adapts a CexIOTicker to a Ticker Object @param ticker The exchange specific ticker @return The ticker
[ "Adapts", "a", "CexIOTicker", "to", "a", "Ticker", "Object" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java#L83-L88
15,597
knowm/XChange
xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java
CexIOAdapters.adaptOrderBook
public static OrderBook adaptOrderBook(CexIODepth depth, CurrencyPair currencyPair) { List<LimitOrder> asks = createOrders(currencyPair, OrderType.ASK, depth.getAsks()); List<LimitOrder> bids = createOrders(currencyPair, OrderType.BID, depth.getBids()); Date date = new Date(depth.getTimestamp() * 1000); return new OrderBook(date, asks, bids); }
java
public static OrderBook adaptOrderBook(CexIODepth depth, CurrencyPair currencyPair) { List<LimitOrder> asks = createOrders(currencyPair, OrderType.ASK, depth.getAsks()); List<LimitOrder> bids = createOrders(currencyPair, OrderType.BID, depth.getBids()); Date date = new Date(depth.getTimestamp() * 1000); return new OrderBook(date, asks, bids); }
[ "public", "static", "OrderBook", "adaptOrderBook", "(", "CexIODepth", "depth", ",", "CurrencyPair", "currencyPair", ")", "{", "List", "<", "LimitOrder", ">", "asks", "=", "createOrders", "(", "currencyPair", ",", "OrderType", ".", "ASK", ",", "depth", ".", "getAsks", "(", ")", ")", ";", "List", "<", "LimitOrder", ">", "bids", "=", "createOrders", "(", "currencyPair", ",", "OrderType", ".", "BID", ",", "depth", ".", "getBids", "(", ")", ")", ";", "Date", "date", "=", "new", "Date", "(", "depth", ".", "getTimestamp", "(", ")", "*", "1000", ")", ";", "return", "new", "OrderBook", "(", "date", ",", "asks", ",", "bids", ")", ";", "}" ]
Adapts Cex.IO Depth to OrderBook Object @param depth Cex.IO order book @param currencyPair The currency pair (e.g. BTC/USD) @return The XChange OrderBook
[ "Adapts", "Cex", ".", "IO", "Depth", "to", "OrderBook", "Object" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java#L126-L132
15,598
knowm/XChange
xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java
CexIOAdapters.adaptWallet
public static Wallet adaptWallet(CexIOBalanceInfo cexIOBalanceInfo) { List<Balance> balances = new ArrayList<>(); for (String ccyName : cexIOBalanceInfo.getBalances().keySet()) { CexIOBalance cexIOBalance = cexIOBalanceInfo.getBalances().get(ccyName); balances.add(adaptBalance(Currency.getInstance(ccyName), cexIOBalance)); } return new Wallet(balances); }
java
public static Wallet adaptWallet(CexIOBalanceInfo cexIOBalanceInfo) { List<Balance> balances = new ArrayList<>(); for (String ccyName : cexIOBalanceInfo.getBalances().keySet()) { CexIOBalance cexIOBalance = cexIOBalanceInfo.getBalances().get(ccyName); balances.add(adaptBalance(Currency.getInstance(ccyName), cexIOBalance)); } return new Wallet(balances); }
[ "public", "static", "Wallet", "adaptWallet", "(", "CexIOBalanceInfo", "cexIOBalanceInfo", ")", "{", "List", "<", "Balance", ">", "balances", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "ccyName", ":", "cexIOBalanceInfo", ".", "getBalances", "(", ")", ".", "keySet", "(", ")", ")", "{", "CexIOBalance", "cexIOBalance", "=", "cexIOBalanceInfo", ".", "getBalances", "(", ")", ".", "get", "(", "ccyName", ")", ";", "balances", ".", "add", "(", "adaptBalance", "(", "Currency", ".", "getInstance", "(", "ccyName", ")", ",", "cexIOBalance", ")", ")", ";", "}", "return", "new", "Wallet", "(", "balances", ")", ";", "}" ]
Adapts CexIOBalanceInfo to Wallet @param cexIOBalanceInfo CexIOBalanceInfo balance @return The account info
[ "Adapts", "CexIOBalanceInfo", "to", "Wallet" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java#L140-L149
15,599
knowm/XChange
xchange-bankera/src/main/java/org/knowm/xchange/bankera/BankeraAdapters.java
BankeraAdapters.adaptTicker
public static Ticker adaptTicker(BankeraTickerResponse ticker, CurrencyPair currencyPair) { BigDecimal high = new BigDecimal(ticker.getTicker().getHigh()); BigDecimal low = new BigDecimal(ticker.getTicker().getLow()); BigDecimal bid = new BigDecimal(ticker.getTicker().getBid()); BigDecimal ask = new BigDecimal(ticker.getTicker().getAsk()); BigDecimal last = new BigDecimal(ticker.getTicker().getLast()); BigDecimal volume = new BigDecimal(ticker.getTicker().getVolume()); Date timestamp = new Date(ticker.getTicker().getTimestamp()); return new Ticker.Builder() .currencyPair(currencyPair) .high(high) .low(low) .bid(bid) .ask(ask) .last(last) .volume(volume) .timestamp(timestamp) .build(); }
java
public static Ticker adaptTicker(BankeraTickerResponse ticker, CurrencyPair currencyPair) { BigDecimal high = new BigDecimal(ticker.getTicker().getHigh()); BigDecimal low = new BigDecimal(ticker.getTicker().getLow()); BigDecimal bid = new BigDecimal(ticker.getTicker().getBid()); BigDecimal ask = new BigDecimal(ticker.getTicker().getAsk()); BigDecimal last = new BigDecimal(ticker.getTicker().getLast()); BigDecimal volume = new BigDecimal(ticker.getTicker().getVolume()); Date timestamp = new Date(ticker.getTicker().getTimestamp()); return new Ticker.Builder() .currencyPair(currencyPair) .high(high) .low(low) .bid(bid) .ask(ask) .last(last) .volume(volume) .timestamp(timestamp) .build(); }
[ "public", "static", "Ticker", "adaptTicker", "(", "BankeraTickerResponse", "ticker", ",", "CurrencyPair", "currencyPair", ")", "{", "BigDecimal", "high", "=", "new", "BigDecimal", "(", "ticker", ".", "getTicker", "(", ")", ".", "getHigh", "(", ")", ")", ";", "BigDecimal", "low", "=", "new", "BigDecimal", "(", "ticker", ".", "getTicker", "(", ")", ".", "getLow", "(", ")", ")", ";", "BigDecimal", "bid", "=", "new", "BigDecimal", "(", "ticker", ".", "getTicker", "(", ")", ".", "getBid", "(", ")", ")", ";", "BigDecimal", "ask", "=", "new", "BigDecimal", "(", "ticker", ".", "getTicker", "(", ")", ".", "getAsk", "(", ")", ")", ";", "BigDecimal", "last", "=", "new", "BigDecimal", "(", "ticker", ".", "getTicker", "(", ")", ".", "getLast", "(", ")", ")", ";", "BigDecimal", "volume", "=", "new", "BigDecimal", "(", "ticker", ".", "getTicker", "(", ")", ".", "getVolume", "(", ")", ")", ";", "Date", "timestamp", "=", "new", "Date", "(", "ticker", ".", "getTicker", "(", ")", ".", "getTimestamp", "(", ")", ")", ";", "return", "new", "Ticker", ".", "Builder", "(", ")", ".", "currencyPair", "(", "currencyPair", ")", ".", "high", "(", "high", ")", ".", "low", "(", "low", ")", ".", "bid", "(", "bid", ")", ".", "ask", "(", "ask", ")", ".", "last", "(", "last", ")", ".", "volume", "(", "volume", ")", ".", "timestamp", "(", "timestamp", ")", ".", "build", "(", ")", ";", "}" ]
Adapts Bankera BankeraTickerResponse to a Ticker @param ticker Specific ticker @param currencyPair BankeraCurrency pair (e.g. ETH/BTC) @return Ticker
[ "Adapts", "Bankera", "BankeraTickerResponse", "to", "a", "Ticker" ]
e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-bankera/src/main/java/org/knowm/xchange/bankera/BankeraAdapters.java#L69-L89