idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
9,200
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 ) ) ; } 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 .
9,201
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 .
9,202
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 ( ) ) { entry . onExpire ( ) ; } else if ( entry . isCancelled ( ) ) { entry . onCancel ( ) ; } else { if ( entry . shouldWait ( ) ) { return ; } OperationService operationService = nodeEngine . getOperationService ( ) ; operationService . run ( op ) ; } entry . setValid ( false ) ; } queue . poll ( ) ; entry = queue . peek ( ) ; if ( entry == null ) { waitSetMap . remove ( key ) ; } } }
executed with an unpark for the same key .
9,203
@ SuppressWarnings ( "checkstyle:npathcomplexity" ) public int doFilter ( EventFilter filter , Data dataKey , Object oldValue , Object dataValue , EntryEventType eventType , String mapNameOrNull ) { if ( filter instanceof MapPartitionLostEventFilter ) { return FILTER_DOES_NOT_MATCH ; } 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 .
9,204
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 ) { 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 { return null ; } } } else if ( ! newValueMatching ) { return null ; } return eventType ; }
other filtering strategy is in place
9,205
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 .
9,206
public long processedCount ( ) { long size = 0 ; for ( Worker worker : workers ) { size += worker . processed . inc ( ) ; } return size ; }
Returns the total number of processed events .
9,207
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 .
9,208
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 { 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 ) { matcher = new Ip4AddressMatcher ( ) ; parseIpv4 ( matcher , address ) ; } else { throw new InvalidAddressException ( address ) ; } return matcher ; }
Gets an AddressMatcher for a given addresses .
9,209
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 .
9,210
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 .
9,211
public void onMemberLeft ( MemberImpl leftMember ) { for ( WaitSet waitSet : waitSetMap . values ( ) ) { waitSet . invalidateAll ( leftMember . getUuid ( ) ) ; } }
invalidated waiting ops will removed from queue eventually by notifiers .
9,212
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
9,213
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
9,214
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 ( ) ; if ( spoofingChecks && ( ! ensureValidBindSource ( connection , remoteEndPoint ) || ! ensureBindNotFromSelf ( connection , remoteEndPoint , thisAddress ) ) ) { return ; } 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 .
9,215
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 .
9,216
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 .
9,217
public MapDataStore getMapDataStore ( String mapName , int partitionId ) { return MapDataStores . createWriteBehindStore ( mapStoreContext , partitionId , writeBehindProcessor ) ; }
todo get this via constructor function .
9,218
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
9,219
public void remove ( int sequence ) { int index = toIndex ( sequence ) ; ringItems [ index ] = null ; isTask [ index ] = false ; head -- ; callableCounter -- ; }
Removes the task with the given sequence
9,220
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
9,221
void replaceTaskWithResult ( int sequence , Object response ) { int index = toIndex ( sequence ) ; 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
9,222
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
9,223
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
9,224
public Object retrieve ( int sequence ) { int index = toIndex ( sequence ) ; checkSequence ( index , sequence ) ; return ringItems [ index ] ; }
Gets the response
9,225
boolean isTask ( int sequence ) { int index = toIndex ( sequence ) ; checkSequence ( index , sequence ) ; return isTask [ index ] ; }
Check if the sequence corresponds to a task
9,226
public static ClientSelector ipSelector ( final String ipMask ) { return new ClientSelector ( ) { public boolean select ( Client client ) { return AddressUtil . matchInterface ( client . getSocketAddress ( ) . getAddress ( ) . getHostAddress ( ) , ipMask ) ; } public String toString ( ) { return "ClientSelector{ipMask:" + ipMask + " }" ; } } ; }
Works with AddressUtil . mathInterface
9,227
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 .
9,228
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 .
9,229
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
9,230
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 .
9,231
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 .
9,232
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 .
9,233
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 .
9,234
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 ( ignored ) ; } } }
Gets the DistributedObjects in this registry . The result is written into result .
9,235
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
9,236
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 .
9,237
void destroy ( ) { for ( DistributedObjectFuture future : proxies . values ( ) ) { if ( ! future . isSetAndInitialized ( ) ) { continue ; } DistributedObject distributedObject = extractDistributedObject ( future ) ; invalidate ( distributedObject ) ; } proxies . clear ( ) ; }
Destroys this proxy registry .
9,238
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 .
9,239
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
9,240
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 .
9,241
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 .
9,242
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
9,243
public void enqueue ( final Callback < T > callback ) { checkIfExecuted ( ) ; this . callback . set ( callback ) ; dispatcher . execute ( new Runnable ( ) { 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
9,244
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 .
9,245
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
9,246
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
9,247
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 .
9,248
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 .
9,249
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 .
9,250
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 .
9,251
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 .
9,252
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 .
9,253
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 .
9,254
public boolean isAbortable ( R result , Throwable failure ) { for ( BiPredicate < R , Throwable > predicate : abortConditions ) { try { if ( predicate . test ( result , failure ) ) return true ; } catch ( Exception t ) { } } return false ; }
Returns whether an execution result can be aborted given the configured abort conditions .
9,255
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 .
9,256
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 .
9,257
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 .
9,258
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 .
9,259
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
9,260
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 .
9,261
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
9,262
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 .
9,263
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
9,264
static void onPermissionsRequested ( Collection < String > grantedPermissions , Collection < String > deniedPermissions ) { if ( instance != null ) { instance . onPermissionRequestGranted ( grantedPermissions ) ; instance . onPermissionRequestDenied ( deniedPermissions ) ; } }
Method called when all the permissions has been requested to the user
9,265
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 .
9,266
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 .
9,267
private List < Thread > getThreadsInGroup ( ThreadGroup group ) { final int activeThreadCount = group . activeCount ( ) ; 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 ) ; } threadArraySize += 100 ; } return Collections . emptyList ( ) ; }
Returns all active threads belonging to a thread group .
9,268
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 .
9,269
public static JUnitCommandLineParseResult parse ( String [ ] args ) { JUnitCommandLineParseResult result = new JUnitCommandLineParseResult ( ) ; result . parseArgs ( args ) ; return result ; }
Parses the arguments .
9,270
public static Matcher < PrintableResult > hasSingleFailureMatching ( final Matcher < Throwable > matcher ) { return new TypeSafeMatcher < PrintableResult > ( ) { 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 .
9,271
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 .
9,272
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 .
9,273
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 .
9,274
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 .
9,275
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 .
9,276
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 .
9,277
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 .
9,278
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 .
9,279
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 .
9,280
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 .
9,281
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 .
9,282
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 .
9,283
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
9,284
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 .
9,285
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 .
9,286
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
9,287
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
9,288
public static void trustAllCerts ( ) throws Exception { TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public java . security . cert . X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( X509Certificate [ ] certs , String authType ) { } } } ; SSLContext sc = SSLContext . getInstance ( "SSL" ) ; sc . init ( null , trustAllCerts , new java . security . SecureRandom ( ) ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( sc . getSocketFactory ( ) ) ; HostnameVerifier allHostsValid = new HostnameVerifier ( ) { public boolean verify ( String hostname , SSLSession session ) { return true ; } } ; 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!
9,289
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 .
9,290
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 ) { return OrderStatus . STOPPED ; } return OrderStatus . NEW ; } if ( order . getFilledSize ( ) . compareTo ( BigDecimal . ZERO ) > 0 && order . getSize ( ) . compareTo ( order . getFilledSize ( ) ) >= 0 ) return OrderStatus . PARTIALLY_FILLED ; return OrderStatus . UNKNOWN ; }
The status from the CoinbaseProOrder object converted to xchange status
9,291
public static CoinbaseProPlaceOrder adaptCoinbaseProStopOrder ( StopOrder stopOrder ) { 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 .
9,292
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
9,293
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
9,294
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
9,295
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
9,296
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
9,297
public static Currency getInstance ( String currencyCode ) { Currency currency = getInstanceNoCreate ( currencyCode . toUpperCase ( ) ) ; if ( currency == null ) { return createCurrency ( currencyCode . toUpperCase ( ) , null , null ) ; } else { return currency ; } }
Returns a Currency instance for the given currency code .
9,298
public Currency getCodeCurrency ( String code ) { if ( code . equals ( this . code ) ) return this ; Currency currency = getInstance ( code ) ; if ( currency . equals ( this ) ) return currency ; if ( ! attributes . codes . contains ( code ) ) throw new IllegalArgumentException ( "Code not listed for this currency" ) ; return new Currency ( code , attributes ) ; }
Gets the equivalent object with the passed code .
9,299
public static AccountInfo adaptAccountInfo ( BitstampBalance bitstampBalance , String userName ) { List < Balance > balances = new ArrayList < > ( ) ; for ( org . knowm . xchange . bitstamp . dto . account . BitstampBalance . Balance b : bitstampBalance . getBalances ( ) ) { Balance xchangeBalance = new Balance ( Currency . getInstance ( b . getCurrency ( ) . toUpperCase ( ) ) , b . getBalance ( ) , b . getAvailable ( ) , b . getReserved ( ) , ZERO , ZERO , b . getBalance ( ) . subtract ( b . getAvailable ( ) ) . subtract ( b . getReserved ( ) ) , ZERO ) ; balances . add ( xchangeBalance ) ; } return new AccountInfo ( userName , bitstampBalance . getFee ( ) , new Wallet ( balances ) ) ; }
Adapts a BitstampBalance to an AccountInfo