idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
3,900
public String getToken ( ) { log . debug ( "DefaultTokenManager getToken()" ) ; if ( ! checkCache ( ) ) { retrieveToken ( ) ; } if ( token == null ) { token = retrieveTokenFromCache ( ) ; } if ( hasTokenExpired ( token ) ) { token = retrieveTokenFromCache ( ) ; } if ( isTokenExpiring ( token ) && ! isAsyncInProgress ( ...
Retrieve the access token String from the OAuth2 token object
3,901
protected synchronized void cacheToken ( final Token token ) { log . debug ( "OAuthTokenManager.cacheToken" ) ; int tokenExpiresInSecs ; try { tokenExpiresInSecs = Integer . parseInt ( token . getExpires_in ( ) ) ; } catch ( NumberFormatException exception ) { tokenExpiresInSecs = 0 ; } long tokenExpirationTime ; try {...
Add the Token object to in - memory cache
3,902
protected boolean hasTokenExpired ( final Token token ) { log . debug ( "OAuthTokenManager.hasTokenExpired" ) ; final long currentTime = System . currentTimeMillis ( ) / 1000L ; if ( Long . valueOf ( token . getExpiration ( ) ) < currentTime ) { retrieveToken ( ) ; return true ; } return false ; }
Check if the current cached token has expired . If it has a synchronous http call is made to the IAM service to retrieve & store a new token
3,903
protected boolean isTokenExpiring ( final Token token ) { log . debug ( "OAuthTokenManager.isTokenExpiring" ) ; final long currentTime = System . currentTimeMillis ( ) / 1000L ; if ( currentTime > token . getRefreshTime ( ) ) { log . debug ( "Token is expiring" ) ; return true ; } else { log . debug ( "Token is not exp...
Check if the current cached token is expiring in less than the given offset . If it is an asynchronous call is made to the IAM service to update the cache .
3,904
protected synchronized void retrieveToken ( ) { log . debug ( "OAuthTokenManager.retrieveToken" ) ; if ( token == null || ( Long . valueOf ( token . getExpiration ( ) ) < System . currentTimeMillis ( ) / 1000L ) ) { log . debug ( "Token is null, retrieving initial token from provider" ) ; boolean tokenRequest = true ; ...
retrieve token from provider . Ensures each thread checks the token is null prior to making the callout to IAM
3,905
protected void submitRefreshTask ( ) { TokenRefreshTask tokenRefreshTask = new TokenRefreshTask ( iamEndpoint , this ) ; executor . execute ( tokenRefreshTask ) ; log . debug ( "Submitted token refresh task" ) ; }
Submits a token refresh task
3,906
public void setClientConfiguration ( ClientConfiguration clientConfiguration ) { this . clientConfiguration = clientConfiguration ; if ( clientConfiguration != null ) { this . httpClientSettings = HttpClientSettings . adapt ( clientConfiguration ) ; if ( getProvider ( ) instanceof DefaultTokenProvider ) { DefaultTokenP...
Set the client config that is been used on the s3client
3,907
public Waiter objectNotExists ( ) { return new WaiterBuilder < GetObjectMetadataRequest , ObjectMetadata > ( ) . withSdkFunction ( new HeadObjectFunction ( client ) ) . withAcceptors ( new HttpFailureStatusAcceptor ( 404 , WaiterState . SUCCESS ) ) . withDefaultPollingStrategy ( new PollingStrategy ( new MaxAttemptsRet...
Builds a ObjectNotExists waiter by using custom parameters waiterParameters and other parameters defined in the waiters specification and then polls until it determines whether the resource entered the desired state or not where polling criteria is bound by either default polling strategy or custom polling strategy .
3,908
protected AmazonServiceException newException ( String message ) throws Exception { Constructor < ? extends AmazonServiceException > constructor = exceptionClass . getConstructor ( String . class ) ; return constructor . newInstance ( message ) ; }
Constructs a new exception object of the type specified in this class s constructor and sets the specified error message .
3,909
private boolean doesStatusMatch ( String status ) { return ( status . equals ( transferListener . getStatus ( xferid ) ) ? true : false ) ; }
Check if the status been passed through to check matches the current status of the xferId within the transferListener
3,910
protected AmazonS3Encryption build ( AwsSyncClientParams clientParams ) { return new AmazonS3EncryptionClient ( new AmazonS3EncryptionClientParamsWrapper ( clientParams , resolveS3ClientOptions ( ) , encryptionMaterials , cryptoConfig != null ? cryptoConfig : new CryptoConfiguration ( ) , kms ) ) ; }
Construct a synchronous implementation of AmazonS3Encryption using the current builder configuration .
3,911
public void setRules ( Map < String , ReplicationRule > rules ) { if ( rules == null ) { throw new IllegalArgumentException ( "Replication rules cannot be null" ) ; } this . rules = new HashMap < String , ReplicationRule > ( rules ) ; }
Sets the replication rules for the Amazon S3 bucket .
3,912
public BucketReplicationConfiguration addRule ( String id , ReplicationRule rule ) { if ( id == null || id . trim ( ) . isEmpty ( ) ) { throw new IllegalArgumentException ( "Rule id cannot be null or empty." ) ; } if ( rule == null ) { throw new IllegalArgumentException ( "Replication rule cannot be null" ) ; } rules ....
Adds a new rule to the replication configuration associated with this Amazon S3 bucket . Returns the updated object .
3,913
public static void registerSigner ( final String signerType , final Class < ? extends Signer > signerClass ) { if ( signerType == null ) { throw new IllegalArgumentException ( "signerType cannot be null" ) ; } if ( signerClass == null ) { throw new IllegalArgumentException ( "signerClass cannot be null" ) ; } SIGNERS ....
Register an implementation class for the given signer type .
3,914
private static Signer lookupAndCreateSigner ( String serviceName , String regionName ) { String signerType = lookUpSignerTypeByServiceAndRegion ( serviceName , regionName ) ; return createSigner ( signerType , serviceName ) ; }
Internal implementation for looking up and creating a signer by service name and region .
3,915
private static Signer createSigner ( String signerType , final String serviceName ) { Class < ? extends Signer > signerClass = SIGNERS . get ( signerType ) ; if ( signerClass == null ) throw new IllegalArgumentException ( "unknown signer type: " + signerType ) ; Signer signer = createSigner ( signerType ) ; if ( signer...
Internal implementation to create a signer by type and service name and configuring it with the service name if applicable .
3,916
public static Signer createSigner ( String signerType , SignerParams params ) { Signer signer = createSigner ( signerType ) ; if ( signer instanceof ServiceAwareSigner ) { ( ( ServiceAwareSigner ) signer ) . setServiceName ( params . getServiceName ( ) ) ; } if ( signer instanceof RegionAwareSigner ) { ( ( RegionAwareS...
Create an instance of the given signer type and initialize it with the given parameters .
3,917
private static Signer createSigner ( String signerType ) { Class < ? extends Signer > signerClass = SIGNERS . get ( signerType ) ; Signer signer ; try { signer = signerClass . newInstance ( ) ; } catch ( InstantiationException ex ) { throw new IllegalStateException ( "Cannot create an instance of " + signerClass . getN...
Create an instance of the given signer .
3,918
public void startEvent ( String eventName ) { eventsBeingProfiled . put ( eventName , TimingInfo . startTimingFullSupport ( System . nanoTime ( ) ) ) ; }
Start an event which will be timed . The startTime and endTime are added to timingInfo only after endEvent is called . For every startEvent there should be a corresponding endEvent . If you start the same event without ending it this will overwrite the old event . i . e . There is no support for recursive events yet . ...
3,919
public void endEvent ( String eventName ) { TimingInfo event = eventsBeingProfiled . get ( eventName ) ; if ( event == null ) { LogFactory . getLog ( getClass ( ) ) . warn ( "Trying to end an event which was never started: " + eventName ) ; return ; } event . endTiming ( ) ; this . timingInfo . addSubMeasurement ( even...
End an event which was previously started . Once ended log how much time the event took . It is illegal to end an Event that was not started . It is good practice to endEvent in a finally block . See Also startEvent .
3,920
public static SSECustomerKey generateSSECustomerKeyForPresignUrl ( String algorithm ) { if ( algorithm == null ) throw new IllegalArgumentException ( ) ; return new SSECustomerKey ( ) . withAlgorithm ( algorithm ) ; }
Constructs a new SSECustomerKey that can be used for generating the presigned URL s .
3,921
public List < T > unmarshall ( JsonUnmarshallerContext context ) throws Exception { if ( context . isInsideResponseHeader ( ) ) { return unmarshallResponseHeaderToList ( context ) ; } return unmarshallJsonToList ( context ) ; }
Unmarshalls the response headers or the json doc in the payload to the list
3,922
private List < T > unmarshallResponseHeaderToList ( JsonUnmarshallerContext context ) throws Exception { String headerValue = context . readText ( ) ; List < T > list = new ArrayList < T > ( ) ; String [ ] headerValues = headerValue . split ( "[,]" ) ; for ( final String headerVal : headerValues ) { list . add ( itemUn...
Un marshalls the response header into the list .
3,923
private List < T > unmarshallJsonToList ( JsonUnmarshallerContext context ) throws Exception { List < T > list = new ArrayList < T > ( ) ; if ( context . getCurrentToken ( ) == JsonToken . VALUE_NULL ) { return null ; } while ( true ) { JsonToken token = context . nextToken ( ) ; if ( token == null ) { return list ; } ...
Unmarshalls the current token in the Json document to list .
3,924
public byte [ ] convertToXmlByteArray ( RequestPaymentConfiguration requestPaymentConfiguration ) { XmlWriter xml = new XmlWriter ( ) ; xml . start ( "RequestPaymentConfiguration" , "xmlns" , Constants . XML_NAMESPACE ) ; Payer payer = requestPaymentConfiguration . getPayer ( ) ; if ( payer != null ) { XmlWriter payerD...
Converts the specified request payment configuration into an XML byte array to send to Amazon S3 .
3,925
protected UploadPartRequest newUploadPartRequest ( PartCreationEvent event , final File part ) { final UploadPartRequest reqUploadPart = new UploadPartRequest ( ) . withBucketName ( req . getBucketName ( ) ) . withFile ( part ) . withKey ( req . getKey ( ) ) . withPartNumber ( event . getPartNumber ( ) ) . withPartSize...
Creates and returns an upload - part request corresponding to a ciphertext file upon a part - creation event .
3,926
public void setFrequency ( InventoryFrequency frequency ) { setFrequency ( frequency == null ? ( String ) null : frequency . toString ( ) ) ; }
Sets the frequency for producing inventory results .
3,927
public static TransferListener getInstance ( String xferId , AsperaTransaction transaction ) { if ( instance == null ) { instance = new TransferListener ( ) ; } if ( transactions . get ( xferId ) != null ) { transactions . get ( xferId ) . add ( transaction ) ; } else { List < AsperaTransaction > transferTransactions =...
Returns TransferListener instance and associates an AsperaTransaction with a Transfer ID . On change of transfer status or bytes transferred the TransferLsitener will fire a progress change event to all progress listeners attached to the AsperaTransaction .
3,928
private boolean isNewSession ( String xferId , String sessionId ) { List < String > currentSessions = transactionSessions . get ( xferId ) ; if ( currentSessions == null ) { List < String > sessions = new ArrayList < String > ( ) ; sessions . add ( sessionId ) ; transactionSessions . put ( xferId , sessions ) ; return ...
Return true if new session for transaction
3,929
private void removeTransactionSession ( String xferId , String sessionId ) { List < String > sessions = transactionSessions . get ( xferId ) ; if ( sessions != null ) { final boolean removal = sessions . remove ( sessionId ) ; if ( removal ) { ascpCount -- ; } } }
Removes the specified transaction session
3,930
public void removeAllTransactionSessions ( String xferId ) { List < String > sessions = transactionSessions . get ( xferId ) ; if ( sessions != null ) sessions . clear ( ) ; }
Removes all sessions for their specified transaction
3,931
private int numberOfSessionsInTransaction ( String xferId ) { int sessionCount = 0 ; List < String > sessions = transactionSessions . get ( xferId ) ; if ( sessions != null ) sessionCount = sessions . size ( ) ; return sessionCount ; }
Returns the number of active sessions for transaction .
3,932
@ SuppressWarnings ( "unchecked" ) private void startScheduler ( ) { scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ SuppressWarnings ( "rawtypes" ) public void run ( ) { Iterator < Entry < String , Long > > it = transactionCallbackTime . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { ...
Start the scheduler to monitor the transactions timestamps within transactionAuditTime
3,933
public void setFormat ( InventoryFormat format ) { setFormat ( format == null ? ( String ) null : format . toString ( ) ) ; }
Sets the output format of the inventory results .
3,934
public Token retrieveToken ( ) { log . debug ( "DefaultTokenProvider retrieveToken()" ) ; try { SSLContext sslContext ; if ( SDKGlobalConfiguration . isCertCheckingDisabled ( ) ) { if ( log . isWarnEnabled ( ) ) { log . warn ( "SSL Certificate checking for endpoints has been " + "explicitly disabled." ) ; } sslContext ...
Retrieve the token using the Apache httpclient in a synchronous manner
3,935
protected boolean needsToLoadCredentials ( ) { if ( credentials == null ) return true ; if ( credentialsExpiration != null ) { if ( isWithinExpirationThreshold ( ) ) return true ; } if ( lastInstanceProfileCheck != null ) { if ( isPastRefreshThreshold ( ) ) return true ; } return false ; }
Returns true if credentials are null credentials are within expiration or if the last attempt to refresh credentials is beyond the refresh threshold .
3,936
private synchronized void fetchCredentials ( ) { if ( ! needsToLoadCredentials ( ) ) return ; JsonNode accessKey ; JsonNode secretKey ; JsonNode node ; JsonNode token ; try { lastInstanceProfileCheck = new Date ( ) ; String credentialsResponse = EC2CredentialsUtils . getInstance ( ) . readResource ( credentailsEndpoint...
Fetches the credentials from the endpoint .
3,937
private void handleError ( String errorMessage , Exception e ) { if ( credentials == null || expired ( ) ) throw new SdkClientException ( errorMessage , e ) ; LOG . debug ( errorMessage , e ) ; }
Handles reporting or throwing an error encountered while requesting credentials from the Amazon EC2 endpoint . The Service could be briefly unavailable for a number of reasons so we need to gracefully handle falling back to valid credentials if they re available and only throw exceptions if we really can t recover .
3,938
public String parseErrorCode ( HttpResponse response , JsonContent jsonContent ) { String errorCodeFromHeader = parseErrorCodeFromHeader ( response . getHeaders ( ) ) ; if ( errorCodeFromHeader != null ) { return errorCodeFromHeader ; } else if ( jsonContent != null ) { return parseErrorCodeFromContents ( jsonContent ....
Parse the error code from the response .
3,939
private String parseErrorCodeFromHeader ( Map < String , String > httpHeaders ) { String headerValue = httpHeaders . get ( X_AMZN_ERROR_TYPE ) ; if ( headerValue != null ) { int separator = headerValue . indexOf ( ':' ) ; if ( separator != - 1 ) { headerValue = headerValue . substring ( 0 , separator ) ; } } return hea...
Attempt to parse the error code from the response headers . Returns null if information is not present in the header .
3,940
public long getCRC32Checksum ( ) { if ( context == null ) { return 0L ; } CRC32ChecksumCalculatingInputStream crc32ChecksumInputStream = ( CRC32ChecksumCalculatingInputStream ) context . getAttribute ( CRC32ChecksumCalculatingInputStream . class . getName ( ) ) ; return crc32ChecksumInputStream == null ? 0L : crc32Chec...
Returns the CRC32 checksum calculated by the underlying CRC32ChecksumCalculatingInputStream .
3,941
public Subclass withIAMEndpoint ( String iamEndpoint ) { this . iamEndpoint = iamEndpoint ; if ( ( this . credentials . getCredentials ( ) instanceof IBMOAuthCredentials ) && ( ( IBMOAuthCredentials ) this . credentials . getCredentials ( ) ) . getTokenManager ( ) instanceof DefaultTokenManager ) { ( ( DefaultTokenMana...
Sets the IAM endpoint to use for token retrieval by the DefaultTokenManager and the DefaultTokenProvider . This should only be over written for a dev or staging environment
3,942
public Subclass withIAMTokenRefresh ( double offset ) { this . iamTokenRefreshOffset = offset ; if ( ( offset > 0 ) && ( this . credentials . getCredentials ( ) instanceof IBMOAuthCredentials ) && ( ( IBMOAuthCredentials ) this . credentials . getCredentials ( ) ) . getTokenManager ( ) instanceof DefaultTokenManager ) ...
Sets the time offset used for IAM token refresh by the DefaultTokenManager . This should only be over written for a dev or staging environment
3,943
public static String load ( ) { JarFile jar = null ; String location = null ; try { jar = createJar ( ) ; String version = jarVersion ( jar ) ; location = EXTRACT_LOCATION_ROOT + SEPARATOR + version ; File extractedLocation = new File ( location ) ; if ( ! extractedLocation . exists ( ) ) { extractJar ( jar , extracted...
Prepares and loads the Aspera library in preparation for its use . May conditionally extract Aspera library jar contents to a location on the local filesystem determined by a combination of the User s home directory and library version . Loads the underlying dynamic library for use by the Aspera library Java bindings
3,944
public static JarFile createJar ( ) throws IOException , URISyntaxException { URL location = faspmanager2 . class . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) ; return new JarFile ( new File ( location . toURI ( ) ) ) ; }
Creates an instance of JarFile which references the Aspera library
3,945
public static String jarVersion ( JarFile jar ) throws IOException { String version = jar . getManifest ( ) . getMainAttributes ( ) . getValue ( Attributes . Name . IMPLEMENTATION_VERSION ) ; if ( version == null ) { version = String . format ( "%d" , System . currentTimeMillis ( ) ) ; } return version ; }
Determines the version associated with this jar
3,946
public static void extractFile ( JarFile jar , JarEntry entry , File destPath ) throws IOException { InputStream in = null ; OutputStream out = null ; try { in = jar . getInputStream ( entry ) ; out = new FileOutputStream ( destPath ) ; byte [ ] buf = new byte [ 1024 ] ; for ( int i = in . read ( buf ) ; i != - 1 ; i =...
Extracts a jar entry from a jar file to a target location on the local file system
3,947
public static List < String > osLibs ( ) { String OS = System . getProperty ( "os.name" ) . toLowerCase ( ) ; if ( OS . indexOf ( "win" ) >= 0 ) { return WINDOWS_DYNAMIC_LIBS ; } else if ( OS . indexOf ( "mac" ) >= 0 ) { return MAC_DYNAMIC_LIBS ; } else if ( OS . indexOf ( "nix" ) >= 0 || OS . indexOf ( "nux" ) >= 0 ||...
Determine which os the jvm is running on
3,948
public static void loadLibrary ( File extractedPath , List < String > candidates ) { for ( String lib : candidates ) { File libPath = new File ( extractedPath , lib ) ; String absPath = libPath . getAbsolutePath ( ) ; log . debug ( "Attempting to load dynamic library: " + absPath ) ; try { System . load ( absPath ) ; l...
Loads a dynamic library into the JVM from a list of candidates
3,949
private List < PartETag > collectPartETags ( ) { final List < PartETag > partETags = new ArrayList < PartETag > ( ) ; for ( Future < PartETag > future : futures ) { try { partETags . add ( future . get ( ) ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to copy part: " + e . getCause ( ) . getMessa...
Collects the Part ETags for initiating the complete multi - part copy request . This is blocking as it waits until all the upload part threads complete .
3,950
public AWSCredentials getCredentials ( ) { if ( credentialProvider != null ) { return credentialProvider . getCredentials ( ) ; } else { credentialProvider = new JsonStaticCredentialsProvider ( credentials ) ; return credentialProvider . getCredentials ( ) ; } }
Returns the IBM credentials .
3,951
public String parseErrorMessage ( HttpResponse httpResponse , JsonNode jsonNode ) { final String headerMessage = httpResponse . getHeader ( X_AMZN_ERROR_MESSAGE ) ; if ( headerMessage != null ) { return headerMessage ; } for ( String field : errorMessageJsonLocations ) { JsonNode value = jsonNode . get ( field ) ; if (...
Parse the error message from the response .
3,952
private void writeBufferToFile ( ) throws IOException { if ( _bufferOffset > 0 ) { List < ByteBuffer > payload = new ArrayList < ByteBuffer > ( 1 ) ; payload . add ( ByteBuffer . wrap ( _buffer , 0 , _bufferOffset ) ) ; NfsWriteResponse response = _nfsFile . write ( _currentOffset , payload , _syncType ) ; int bytesWri...
Write the buffer contents to the file and reset the buffer afterwards .
3,953
private void checkRpcReply ( ) throws RpcException { if ( _replyStatus != ReplyStatus . MSG_ACCEPTED . getValue ( ) ) { String msg = String . format ( "RPC call is REJECTED, rejectStat=%d" , _rejectStatus ) ; throw new RpcException ( RejectStatus . fromValue ( _rejectStatus ) , msg ) ; } else { if ( _acceptStatus != Ac...
Check whether the reply is successful . If not log and throw exception . the function is usually called after unmarshalling .
3,954
static void putRecordMarkingAndSend ( Channel channel , Xdr rpcRequest ) { List < ByteBuffer > buffers = new LinkedList < > ( ) ; buffers . add ( ByteBuffer . wrap ( rpcRequest . getBuffer ( ) , 0 , rpcRequest . getOffset ( ) ) ) ; if ( rpcRequest . getPayloads ( ) != null ) { buffers . addAll ( rpcRequest . getPayload...
Insert record marking into rpcRequest and then send to tcp stream .
3,955
static Xdr removeRecordMarking ( byte [ ] bytes ) { Xdr toReturn = new Xdr ( bytes . length ) ; Xdr input = new Xdr ( bytes ) ; long fragSize ; boolean lastFragment = false ; input . setOffset ( 0 ) ; int inputOff = input . getOffset ( ) ; while ( ! lastFragment ) { fragSize = input . getUnsignedInt ( ) ; lastFragment ...
Remove record marking from the byte array and convert to an Xdr .
3,956
public void marshalling ( Xdr xdr ) { marshalling ( xdr , _mode ) ; marshalling ( xdr , _uid ) ; marshalling ( xdr , _gid ) ; if ( _size != null ) { xdr . putBoolean ( true ) ; xdr . putLong ( _size . longValue ( ) ) ; } else { xdr . putBoolean ( false ) ; } marshalling ( xdr , _atime ) ; marshalling ( xdr , _mtime ) ;...
Set Xdr fields for the rpc call .
3,957
public static NfsCreateMode fromValue ( int value ) { NfsCreateMode createMode = VALUES . get ( value ) ; if ( createMode == null ) { createMode = new NfsCreateMode ( value ) ; VALUES . put ( value , createMode ) ; } return createMode ; }
Convenience function to get the instance from the int create mode value .
3,958
public static int queryPortFromPortMap ( int program , int version , String serverIP ) throws IOException { GetPortResponse response = null ; GetPortRequest request = new GetPortRequest ( program , version ) ; for ( int i = 0 ; i < _maxRetry ; ++ i ) { try { Xdr portmapXdr = new Xdr ( PORTMAP_MAX_REQUEST_SIZE ) ; reque...
Given program and version of a service query its tcp port number
3,959
private static void handleRpcException ( RpcException e , int attemptNumber , String server ) throws IOException { String messageStart ; if ( ! ( e . getStatus ( ) . equals ( RpcStatus . NETWORK_ERROR ) ) ) { messageStart = "network" ; } else { if ( attemptNumber + 1 < _maxRetry ) { return ; } messageStart = "rpc" ; } ...
Decide whether to retry or throw exception .
3,960
private static NfsPreOpAttributes makePreOpAttributes ( Xdr xdr ) { NfsPreOpAttributes preOpAttributes = null ; if ( ( xdr != null ) && xdr . getBoolean ( ) ) { preOpAttributes = new NfsPreOpAttributes ( xdr ) ; } return preOpAttributes ; }
Extracts the pre - operation attributes .
3,961
private static NfsGetAttributes makeAttributes ( Xdr xdr ) { NfsGetAttributes attributes = null ; if ( xdr != null ) { attributes = NfsResponseBase . makeNfsGetAttributes ( xdr ) ; } return attributes ; }
Extracts the post - operation attributes .
3,962
public void putInt ( int i ) { _buffer [ _offset ++ ] = ( byte ) ( i >>> 24 ) ; _buffer [ _offset ++ ] = ( byte ) ( i >> 16 ) ; _buffer [ _offset ++ ] = ( byte ) ( i >> 8 ) ; _buffer [ _offset ++ ] = ( byte ) i ; }
Put an integer into the buffer
3,963
public void putUnsignedInt ( long i ) { _buffer [ _offset ++ ] = ( byte ) ( i >>> 24 & 0xff ) ; _buffer [ _offset ++ ] = ( byte ) ( i >> 16 ) ; _buffer [ _offset ++ ] = ( byte ) ( i >> 8 ) ; _buffer [ _offset ++ ] = ( byte ) i ; }
Put an unsigned integer into the buffer Note that Java has no unsigned integer type so we must pass it as a long .
3,964
public long getLong ( ) { return ( ( long ) ( _buffer [ _offset ++ ] & 0xff ) << 56 | ( long ) ( _buffer [ _offset ++ ] & 0xff ) << 48 | ( long ) ( _buffer [ _offset ++ ] & 0xff ) << 40 | ( long ) ( _buffer [ _offset ++ ] & 0xff ) << 32 | ( long ) ( _buffer [ _offset ++ ] & 0xff ) << 24 | ( long ) ( _buffer [ _offset +...
Get a long from the buffer
3,965
public void putLong ( long i ) { _buffer [ _offset ++ ] = ( byte ) ( i >>> 56 ) ; _buffer [ _offset ++ ] = ( byte ) ( ( i >> 48 ) & 0xff ) ; _buffer [ _offset ++ ] = ( byte ) ( ( i >> 40 ) & 0xff ) ; _buffer [ _offset ++ ] = ( byte ) ( ( i >> 32 ) & 0xff ) ; _buffer [ _offset ++ ] = ( byte ) ( ( i >> 24 ) & 0xff ) ; _b...
Put a long into the buffer
3,966
public String getString ( ) { int len = getInt ( ) ; String s = new String ( _buffer , _offset , len , RpcRequest . CHARSET ) ; skip ( len ) ; return s ; }
Get a string from the buffer
3,967
public byte [ ] getByteArray ( ) { int lengthToCopy = getInt ( ) ; byte [ ] byteArray = ( lengthToCopy == 0 ) ? null : new byte [ lengthToCopy ] ; getBytes ( lengthToCopy , byteArray , 0 ) ; return byteArray ; }
Get a counted array of bytes from the buffer
3,968
public void getBytes ( int lengthToCopy , byte [ ] copyArray , int copyOffset ) { if ( lengthToCopy > 0 ) { System . arraycopy ( _buffer , _offset , copyArray , copyOffset , lengthToCopy ) ; skip ( lengthToCopy ) ; } }
Get bytes from the xdr buffer to the input buffer
3,969
public void putByteArray ( byte [ ] b , int boff , int len ) { putInt ( len ) ; putBytes ( b , boff , len ) ; }
Put a counted array of bytes into the buffer
3,970
public void putBytes ( byte [ ] b , int boff , int len ) { System . arraycopy ( b , boff , _buffer , _offset , len ) ; skip ( len ) ; }
Put a counted array of bytes into the buffer . The length is not encoded .
3,971
public void putPayloads ( List < ByteBuffer > payloads , int size ) { putInt ( size ) ; if ( _payloads == null ) { _payloads = payloads ; } else { _payloads . addAll ( payloads ) ; } _payloadsSize += size ; }
add payloads more than one can be added .
3,972
protected void connect ( ) throws RpcException { if ( _state . equals ( State . CONNECTED ) ) { return ; } final ChannelFuture oldChannelFuture = _channelFuture ; if ( LOG . isDebugEnabled ( ) ) { String logPrefix = _usePrivilegedPort ? "usePrivilegedPort " : "" ; LOG . debug ( "{}connecting to {}" , logPrefix , getRem...
If there is no current connection start a new tcp connection asynchronously .
3,973
protected void close ( ) { _state = State . DISCONNECTED ; shutdown ( ) ; NetMgr . getInstance ( ) . dropConnection ( InetSocketAddress . createUnresolved ( _remoteHost , _port ) ) ; notifyAllPendingSenders ( "Channel closed, connection closing." ) ; }
This is called when the connection should be closed .
3,974
protected void notifySender ( Integer xid , Xdr response ) { ChannelFuture future = _futureMap . get ( xid ) ; if ( future != null ) { _responseMap . put ( xid , response ) ; future . setSuccess ( ) ; } }
Update the response map with the response and notify the thread waiting for the response . Do nothing if the future has been removed .
3,975
protected void notifyAllPendingSenders ( String message ) { for ( ChannelFuture future : _futureMap . values ( ) ) { future . setFailure ( new Error ( message ) ) ; } }
Notify all the senders of all pending requests
3,976
private Channel bindToPrivilegedPort ( ) throws RpcException { System . out . println ( "Attempting to use privileged port." ) ; for ( int port = 1023 ; port > 0 ; -- port ) { try { ChannelPipeline pipeline = _clientBootstrap . getPipelineFactory ( ) . getPipeline ( ) ; Channel channel = _clientBootstrap . getFactory (...
This attempts to bind to privileged ports starting with 1023 and working downwards and returns when the first binding succeeds .
3,977
protected List < F > getChildFiles ( List < String > childNames ) throws IOException { if ( childNames == null ) { return null ; } List < F > childFiles = new ArrayList < F > ( childNames . size ( ) ) ; for ( String childName : childNames ) { childFiles . add ( getChildFile ( childName ) ) ; } return childFiles ; }
Conversion method .
3,978
private void setParentFileAndName ( F parentFile , String name , LinkTracker < N , F > linkTracker ) throws IOException { if ( parentFile != null ) { parentFile = parentFile . followLinks ( linkTracker ) ; if ( StringUtils . isBlank ( name ) || "." . equals ( name ) ) { name = parentFile . getName ( ) ; parentFile = pa...
This method handles special cases such as symbolic links in the parent directory empty filenames or the special names . and .. . The algorithm required is simplified by the fact that special cases for the parent file are handled before this is called as the path is always resolved from the bottom up . This means that t...
3,979
private void setFileHandle ( ) { byte [ ] fileHandle = null ; if ( _isRootFile ) { fileHandle = getNfs ( ) . getRootFileHandle ( ) ; } else { try { if ( getParentFile ( ) . getFileHandle ( ) != null ) { fileHandle = getNfs ( ) . wrapped_getLookup ( makeLookupRequest ( ) ) . getFileHandle ( ) ; } } catch ( IOException e...
Set the file handle from the _path value
3,980
public void callRpcWrapped ( S request , RpcResponseHandler < ? extends T > responseHandler ) throws IOException { for ( int i = 0 ; i < _maximumRetries ; ++ i ) { try { callRpcChecked ( request , responseHandler ) ; return ; } catch ( RpcException e ) { handleRpcException ( e , i ) ; } } }
Make the wrapped call and unmarshall the returned Xdr to a response getting the IP key from the request . If an RPC Exception is being thrown and retries remain then log the exception and retry .
3,981
public void callRpcNaked ( S request , T response ) throws IOException { callRpcNaked ( request , response , chooseIP ( request . getIpKey ( ) ) ) ; }
Make the call using the Request ip key to determine the IP address for communication .
3,982
public void callRpcNaked ( S request , T response , String ipAddress ) throws RpcException { Xdr xdr = new Xdr ( _maximumRequestSize ) ; request . marshalling ( xdr ) ; response . unmarshalling ( callRpc ( ipAddress , xdr , request . isUsePrivilegedPort ( ) ) ) ; }
Make the call to a specified IP address .
3,983
public Xdr callRpc ( String serverIP , Xdr xdrRequest , boolean usePrivilegedPort ) throws RpcException { return NetMgr . getInstance ( ) . sendAndWait ( serverIP , _port , usePrivilegedPort , xdrRequest , _rpcTimeout ) ; }
Basic RPC call functionality only .
3,984
private void callRpcChecked ( S request , RpcResponseHandler < ? extends T > responseHandler , String ipAddress ) throws IOException { LOG . debug ( "server {}, port {}, request {}" , _server , _port , request ) ; callRpcNaked ( request , responseHandler . getNewResponse ( ) , ipAddress ) ; if ( LOG . isDebugEnabled ( ...
The base functionality used by all NFS calls which does basic return code checking and throws an exception if this does not pass . Verbose logging is also handled here . This method is not used by Portmap Mount and Unmount calls .
3,985
private void handleRpcException ( RpcException e , int attemptNumber ) throws IOException { String messageStart ; if ( ! ( e . getStatus ( ) . equals ( RpcStatus . NETWORK_ERROR ) ) ) { messageStart = "rpc" ; } else { if ( attemptNumber + 1 < _maximumRetries ) { try { int waitTime = _retryWait * ( attemptNumber + 1 ) ;...
Decide whether to retry or throw an exception .
3,986
private String [ ] probeIps ( ) { Set < String > ips = new TreeSet < String > ( ) ; for ( int i = 0 ; i < 32 ; ++ i ) { InetSocketAddress sa = new InetSocketAddress ( _server , _port ) ; ips . add ( sa . getAddress ( ) . getHostAddress ( ) ) ; } if ( LOG . isDebugEnabled ( ) ) { StringBuffer sb = new StringBuffer ( ) ;...
Find possible IP addresses for communicating with the server .
3,987
public Xdr sendAndWait ( String serverIP , int port , boolean usePrivilegedPort , Xdr xdrRequest , int timeout ) throws RpcException { InetSocketAddress key = InetSocketAddress . createUnresolved ( serverIP , port ) ; Map < InetSocketAddress , Connection > connectionMap = usePrivilegedPort ? _privilegedConnectionMap : ...
Basic RPC call functionality only . Send the request creating a new connection as necessary and return the raw Xdr returned .
3,988
public void shutdown ( ) { for ( Connection connection : _connectionMap . values ( ) ) { connection . shutdown ( ) ; } for ( Connection connection : _privilegedConnectionMap . values ( ) ) { connection . shutdown ( ) ; } _factory . releaseExternalResources ( ) ; }
Called when the application is being shut down .
3,989
private void loadBytesAsNeeded ( ) throws IOException { if ( available ( ) <= 0 ) { _isEof = true ; } while ( ( ! _isEof ) && ( bytesLeftInBuffer ( ) <= 0 ) ) { _currentBufferPosition = 0 ; NfsReadResponse response = _file . read ( _offset , _bytes . length , _bytes , _currentBufferPosition ) ; _bytesInBuffer = respons...
If the buffer has no more bytes to be read and there are bytes available in the file load more bytes .
3,990
private void checkForBlank ( String value , String name ) { if ( StringUtils . isBlank ( value ) ) { throw new IllegalArgumentException ( name + " cannot be empty" ) ; } }
Convenience method to check String parameters that cannot be blank .
3,991
private void prepareRootFhAndNfsPort ( ) throws IOException { if ( ! _prepareLock . tryLock ( ) ) { return ; } try { _port = getNfsPortFromServer ( ) ; _rpcWrapper . setPort ( _port ) ; _rootFileHandle = lookupRootHandle ( ) ; } finally { _prepareLock . unlock ( ) ; } }
Query the port and root file handle for NFS server .
3,992
private boolean handleRpcException ( RpcException e , int attemptNumber ) throws IOException { boolean tryPrivilegedPort = e . getStatus ( ) . equals ( RejectStatus . AUTH_ERROR ) ; boolean networkError = e . getStatus ( ) . equals ( RpcStatus . NETWORK_ERROR ) ; boolean retry = ( tryPrivilegedPort || networkError ) &&...
Decide whether to retry or throw an exception
3,993
public int read ( String path , byte [ ] fileHandle , long offset , int length , final byte [ ] data , final int pos , final MutableBoolean eof ) throws IOException { Nfs3ReadRequest request = new Nfs3ReadRequest ( fileHandle , offset , length , _credential ) ; NfsResponseHandler < Nfs3ReadResponse > responseHandler = ...
Read data from a file handle
3,994
synchronized final F addLink ( String path ) throws IOException { if ( ++ linksTraversed > MAXSYMLINKS ) { throw new IllegalArgumentException ( "Too many links to follow (> " + MAXSYMLINKS + ")." ) ; } F resolvedPath = _resolvedPaths . get ( path ) ; if ( resolvedPath == null ) { for ( String unresolvedPath : _unresolv...
Checks for problems . If the link has already been resolved it returns the final file . If not it adds the link path to the list of unresolved paths that have been seen while evaluating this chain .
3,995
synchronized void addResolvedPath ( String path , F file ) { _resolvedPaths . put ( path , file ) ; _unresolvedPaths . remove ( path ) ; }
After each link is completely resolved the linkTracker caller should call this method to store that resolved path so that it can be resolved directly the next time is is seen .
3,996
public static NfsType fromValue ( int value ) { NfsType nfsType = VALUES . get ( value ) ; if ( nfsType == null ) { nfsType = new NfsType ( value ) ; VALUES . put ( value , nfsType ) ; } return nfsType ; }
Convenience function to get the instance from the int type value .
3,997
private static boolean isMappingExist ( RestHighLevelClient client , String index ) throws Exception { GetMappingsResponse mapping = client . indices ( ) . getMapping ( new GetMappingsRequest ( ) . indices ( index ) , RequestOptions . DEFAULT ) ; if ( mapping . mappings ( ) . isEmpty ( ) ) { return false ; } MappingMet...
Check if an index already exist
3,998
public static List < String > findTypes ( String index ) throws IOException , URISyntaxException { return findTypes ( Defaults . ConfigDir , index ) ; }
Find all types within an index in default classpath dir
3,999
private void initAliases ( ) throws Exception { if ( aliases != null && aliases . length > 0 ) { for ( String aliasIndex : aliases ) { Tuple < String , String > aliasIndexSplitted = computeAlias ( aliasIndex ) ; createAlias ( client . getLowLevelClient ( ) , aliasIndexSplitted . v2 ( ) , aliasIndexSplitted . v1 ( ) ) ;...
Init aliases if needed .