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 ( ) ) { if ( null != token . getRefresh_token ( ) ) { this . asyncInProgress = true ; submitRefreshTask ( ) ; } else { retrieveToken ( ) ; token = retrieveTokenFromCache ( ) ; } } if ( token . getAccess_token ( ) != null && ! token . getAccess_token ( ) . isEmpty ( ) ) { return token . getAccess_token ( ) ; } else if ( token . getDelegated_refresh_token ( ) != null && ! token . getDelegated_refresh_token ( ) . isEmpty ( ) ) { return token . getDelegated_refresh_token ( ) ; } else if ( token . getIms_token ( ) != null && ! token . getIms_token ( ) . isEmpty ( ) ) { return token . getIms_token ( ) ; } else { return token . getUaa_token ( ) ; } }
|
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 { tokenExpirationTime = Long . parseLong ( token . getExpiration ( ) ) ; } catch ( NumberFormatException exception ) { tokenExpirationTime = 0 ; } long refreshBeforeExpirySecs = ( long ) ( tokenExpiresInSecs * this . iamRefreshOffset ) ; long tokenRefreshTime = tokenExpirationTime - refreshBeforeExpirySecs ; token . setRefreshTime ( tokenRefreshTime ) ; token . setExpirationTime ( tokenExpirationTime ) ; setTokenCache ( token ) ; }
|
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 expiring." + token . getRefreshTime ( ) + " > " + currentTime ) ; return false ; } }
|
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 ; int retryCount = 0 ; while ( tokenRequest && retryCount < this . iamMaxRetry ) { try { ++ retryCount ; token = provider . retrieveToken ( ) ; tokenRequest = false ; } catch ( OAuthServiceException exception ) { log . debug ( "Exception retrieving IAM token. Returned status code " + exception . getStatusCode ( ) + "Retry attempt " + retryCount ) ; tokenRequest = shouldRetry ( exception . getStatusCode ( ) ) ? true : false ; if ( ! tokenRequest || retryCount == this . iamMaxRetry ) throw exception ; } } if ( null == token ) throw new OAuthServiceException ( "Null token returned by the Token Provider" ) ; cacheToken ( token ) ; } }
|
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 ) { DefaultTokenProvider defaultProvider = ( DefaultTokenProvider ) getProvider ( ) ; defaultProvider . setHttpClientSettings ( httpClientSettings ) ; } if ( getProvider ( ) instanceof DelegateTokenProvider ) { DelegateTokenProvider delegateProvider = ( DelegateTokenProvider ) getProvider ( ) ; delegateProvider . setHttpClientSettings ( httpClientSettings ) ; } } }
|
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 MaxAttemptsRetryStrategy ( 20 ) , new FixedDelayStrategy ( 5 ) ) ) . withExecutorService ( executorService ) . build ( ) ; }
|
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 . put ( id , rule ) ; return this ; }
|
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 . put ( signerType , signerClass ) ; }
|
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 instanceof ServiceAwareSigner ) { ( ( ServiceAwareSigner ) signer ) . setServiceName ( serviceName ) ; } return 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 ) { ( ( RegionAwareSigner ) signer ) . setRegionName ( params . getRegionName ( ) ) ; } return signer ; }
|
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 . getName ( ) , ex ) ; } catch ( IllegalAccessException ex ) { throw new IllegalStateException ( "Cannot create an instance of " + signerClass . getName ( ) , ex ) ; } return signer ; }
|
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 . Having said that if you start and end an event in that sequence multiple times all events are logged in timingInfo in that order .
|
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 ( eventName , TimingInfo . unmodifiableTimingInfo ( event . getStartTimeNano ( ) , event . getEndTimeNano ( ) ) ) ; }
|
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 ( itemUnmarshaller . unmarshall ( new JsonUnmarshallerContext ( ) { public String readText ( ) { return headerVal ; } } ) ) ; } return list ; }
|
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 ; } if ( token == END_ARRAY ) { return list ; } else { list . add ( itemUnmarshaller . unmarshall ( context ) ) ; } } }
|
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 payerDocumentElement = xml . start ( "Payer" ) ; payerDocumentElement . value ( payer . toString ( ) ) ; payerDocumentElement . end ( ) ; } xml . end ( ) ; return xml . getBytes ( ) ; }
|
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 ( part . length ( ) ) . withLastPart ( event . isLastPart ( ) ) . withUploadId ( uploadId ) . withObjectMetadata ( req . getUploadPartMetadata ( ) ) ; return reqUploadPart ; }
|
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 = new ArrayList < AsperaTransaction > ( ) ; transferTransactions . add ( transaction ) ; transactions . put ( xferId , transferTransactions ) ; } return instance ; }
|
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 true ; } else if ( ! currentSessions . contains ( sessionId ) ) { currentSessions . add ( sessionId ) ; return true ; } else { return false ; } }
|
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 ( ) ) { Map . Entry pair = ( Map . Entry ) it . next ( ) ; if ( ( System . currentTimeMillis ( ) - ( Long ) pair . getValue ( ) ) > 5000 ) { final String xferId = ( String ) pair . getKey ( ) ; it . remove ( ) ; status . put ( xferId , "ERROR" ) ; ascpCount -= numberOfSessionsInTransaction ( xferId ) ; removeAllTransactionSessions ( xferId ) ; removeTransactionProgressData ( xferId ) ; log . error ( "Status marked as [ERROR] for xferId [" + xferId + "] after not reporting for over 5 seconds" ) ; } } } } , 5 , 5 , TimeUnit . SECONDS ) ; }
|
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 = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( null , new TrustManager [ ] { new TrustingX509TrustManager ( ) } , null ) ; } else { sslContext = SSLContexts . createDefault ( ) ; } SSLConnectionSocketFactory sslsf = new SdkTLSSocketFactory ( sslContext , new DefaultHostnameVerifier ( ) ) ; HttpClientBuilder builder = HttpClientBuilder . create ( ) ; if ( httpClientSettings != null ) { DefaultTokenManager . addProxyConfig ( builder , httpClientSettings ) ; } HttpClient client = builder . setSSLSocketFactory ( sslsf ) . build ( ) ; HttpPost post = new HttpPost ( iamEndpoint ) ; post . setHeader ( "Authorization" , BASIC_AUTH ) ; post . setHeader ( "Content-Type" , CONTENT_TYPE ) ; post . setHeader ( "Accept" , ACCEPT ) ; List < NameValuePair > urlParameters = new ArrayList < NameValuePair > ( ) ; urlParameters . add ( new BasicNameValuePair ( "grant_type" , GRANT_TYPE ) ) ; urlParameters . add ( new BasicNameValuePair ( "response_type" , RESPONSE_TYPE ) ) ; urlParameters . add ( new BasicNameValuePair ( "apikey" , apiKey ) ) ; post . setEntity ( new UrlEncodedFormEntity ( urlParameters ) ) ; final HttpResponse response = client . execute ( post ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) != 200 ) { log . info ( "Response code= " + response . getStatusLine ( ) . getStatusCode ( ) + ", Reason= " + response . getStatusLine ( ) . getReasonPhrase ( ) + ".Throwing OAuthServiceException" ) ; OAuthServiceException exception = new OAuthServiceException ( "Token retrieval from IAM service failed" ) ; exception . setStatusCode ( response . getStatusLine ( ) . getStatusCode ( ) ) ; exception . setStatusMessage ( response . getStatusLine ( ) . getReasonPhrase ( ) ) ; throw exception ; } final HttpEntity entity = response . getEntity ( ) ; final String resultStr = EntityUtils . toString ( entity ) ; final ObjectMapper mapper = new ObjectMapper ( ) ; final Token token = mapper . readValue ( resultStr , Token . class ) ; return token ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } catch ( ClientProtocolException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( NoSuchAlgorithmException e ) { e . printStackTrace ( ) ; } catch ( KeyManagementException e ) { e . printStackTrace ( ) ; } return null ; }
|
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 ( credentailsEndpointProvider . getCredentialsEndpoint ( ) , credentailsEndpointProvider . getRetryPolicy ( ) ) ; node = Jackson . jsonNodeOf ( credentialsResponse ) ; accessKey = node . get ( ACCESS_KEY_ID ) ; secretKey = node . get ( SECRET_ACCESS_KEY ) ; token = node . get ( TOKEN ) ; if ( null == accessKey || null == secretKey ) { throw new SdkClientException ( "Unable to load credentials." ) ; } if ( null != token ) { credentials = new BasicSessionCredentials ( accessKey . asText ( ) , secretKey . asText ( ) , token . asText ( ) ) ; } else { credentials = new BasicAWSCredentials ( accessKey . asText ( ) , secretKey . asText ( ) ) ; } JsonNode expirationJsonNode = node . get ( "Expiration" ) ; if ( null != expirationJsonNode ) { String expiration = expirationJsonNode . asText ( ) ; expiration = expiration . replaceAll ( "\\+0000$" , "Z" ) ; try { credentialsExpiration = DateUtils . parseISO8601Date ( expiration ) ; } catch ( Exception ex ) { handleError ( "Unable to parse credentials expiration date from Amazon EC2 instance" , ex ) ; } } } catch ( JsonMappingException e ) { handleError ( "Unable to parse response returned from service endpoint" , e ) ; } catch ( IOException e ) { handleError ( "Unable to load credentials from service endpoint" , e ) ; } catch ( URISyntaxException e ) { handleError ( "Unable to load credentials from service endpoint" , e ) ; } }
|
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 . getJsonNode ( ) ) ; } else { return null ; } }
|
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 headerValue ; }
|
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 : crc32ChecksumInputStream . getCRC32Checksum ( ) ; }
|
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 ) { ( ( DefaultTokenManager ) ( ( IBMOAuthCredentials ) this . credentials . getCredentials ( ) ) . getTokenManager ( ) ) . setIamEndpoint ( iamEndpoint ) ; if ( ( ( DefaultTokenManager ) ( ( IBMOAuthCredentials ) this . credentials . getCredentials ( ) ) . getTokenManager ( ) ) . getProvider ( ) instanceof DefaultTokenProvider ) { ( ( DefaultTokenProvider ) ( ( DefaultTokenManager ) ( ( IBMOAuthCredentials ) this . credentials . getCredentials ( ) ) . getTokenManager ( ) ) . getProvider ( ) ) . setIamEndpoint ( iamEndpoint ) ; ( ( DefaultTokenProvider ) ( ( DefaultTokenManager ) ( ( IBMOAuthCredentials ) this . credentials . getCredentials ( ) ) . getTokenManager ( ) ) . getProvider ( ) ) . retrieveToken ( ) ; } } return getSubclass ( ) ; }
|
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 ) { ( ( DefaultTokenManager ) ( ( IBMOAuthCredentials ) this . credentials . getCredentials ( ) ) . getTokenManager ( ) ) . setIamRefreshOffset ( iamTokenRefreshOffset ) ; } return getSubclass ( ) ; }
|
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 , extractedLocation ) ; } loadLibrary ( extractedLocation , osLibs ( ) ) ; } catch ( Exception e ) { throw new AsperaLibraryLoadException ( "Unable to load Aspera Library" , e ) ; } finally { if ( jar != null ) { try { jar . close ( ) ; } catch ( IOException e ) { log . warn ( "Unable to close Aspera jar file after loading" , e ) ; } } } return location ; }
|
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 = in . read ( buf ) ) { out . write ( buf , 0 , i ) ; } } finally { if ( in != null ) { in . close ( ) ; } if ( out != null ) { out . close ( ) ; } } if ( entry . getName ( ) . equals ( "ascp" ) ) { destPath . setExecutable ( true ) ; destPath . setWritable ( true ) ; } }
|
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 || OS . indexOf ( "aix" ) > 0 ) { return UNIX_DYNAMIC_LIBS ; } else { throw new AsperaLibraryLoadException ( "OS is not supported for Aspera" ) ; } }
|
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 ) ; log . info ( "Loaded dynamic library: " + absPath ) ; return ; } catch ( UnsatisfiedLinkError e ) { log . debug ( "Unable to load dynamic library: " + absPath , e ) ; } } throw new RuntimeException ( "Failed to load Aspera dynamic library from candidates " + candidates + " at location: " + extractedPath ) ; }
|
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 ( ) . getMessage ( ) , e . getCause ( ) ) ; } } return partETags ; }
|
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 ( value != null && value . isTextual ( ) ) { return value . asText ( ) ; } } return null ; }
|
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 bytesWritten = response . getCount ( ) ; _currentOffset += bytesWritten ; _bufferOffset -= bytesWritten ; if ( 0 != _bufferOffset ) { System . arraycopy ( _buffer , bytesWritten , _buffer , 0 , _bufferOffset ) ; } } }
|
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 != AcceptStatus . SUCCESS . getValue ( ) ) { String msg = String . format ( "RPC call is ACCEPTED, but the status is not success, acceptStat=%d" , _acceptStatus ) ; throw new RpcException ( AcceptStatus . fromValue ( _acceptStatus ) , msg ) ; } } }
|
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 . getPayloads ( ) ) ; } List < ByteBuffer > outBuffers = new ArrayList < > ( ) ; int bytesToWrite = 0 ; int remainingBuffers = buffers . size ( ) ; boolean isLast = false ; for ( ByteBuffer buffer : buffers ) { if ( bytesToWrite + buffer . remaining ( ) > MTU_SIZE ) { if ( outBuffers . isEmpty ( ) ) { LOG . error ( "too big single byte buffer {}" , buffer . remaining ( ) ) ; throw new IllegalArgumentException ( String . format ( "too big single byte buffer %d" , buffer . remaining ( ) ) ) ; } else { sendBuffers ( channel , bytesToWrite , outBuffers , isLast ) ; bytesToWrite = 0 ; outBuffers . clear ( ) ; } } outBuffers . add ( buffer ) ; bytesToWrite += buffer . remaining ( ) ; remainingBuffers -= 1 ; isLast = ( remainingBuffers == 0 ) ; } if ( ! outBuffers . isEmpty ( ) ) { sendBuffers ( channel , bytesToWrite , outBuffers , true ) ; } }
|
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 = isLastFragment ( fragSize ) ; fragSize = maskFragmentSize ( fragSize ) ; toReturn . putBytes ( input . getBuffer ( ) , input . getOffset ( ) , ( int ) fragSize ) ; inputOff += fragSize ; input . setOffset ( inputOff ) ; } int off = toReturn . getOffset ( ) ; toReturn . setOffset ( 0 ) ; int xid = toReturn . getInt ( ) ; toReturn . setXid ( xid ) ; toReturn . setOffset ( off ) ; return toReturn ; }
|
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 ) ; request . marshalling ( portmapXdr ) ; Xdr reply = NetMgr . getInstance ( ) . sendAndWait ( serverIP , PMAP_PORT , _usePrivilegedPort , portmapXdr , PORTMAP_RPC_TIMEOUT ) ; response = new GetPortResponse ( ) ; response . unmarshalling ( reply ) ; } catch ( RpcException e ) { handleRpcException ( e , i , serverIP ) ; } } int port = response . getPort ( ) ; if ( port == 0 ) { String msg = String . format ( "No registry entry for program: %s, version: %s, serverIP: %s" , program , version , serverIP ) ; throw new IOException ( msg ) ; } return port ; }
|
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" ; } throw new IOException ( String . format ( "%s error, server: %s, RPC error: %s" , messageStart , server , e . getMessage ( ) ) , e ) ; }
|
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 ++ ] & 0xff ) << 16 | ( long ) ( _buffer [ _offset ++ ] & 0xff ) << 8 | ( long ) ( _buffer [ _offset ++ ] & 0xff ) ) ; }
|
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 ) ; _buffer [ _offset ++ ] = ( byte ) ( ( i >> 16 ) & 0xff ) ; _buffer [ _offset ++ ] = ( byte ) ( ( i >> 8 ) & 0xff ) ; _buffer [ _offset ++ ] = ( byte ) ( i & 0xff ) ; }
|
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 , getRemoteAddress ( ) ) ; } _state = State . CONNECTING ; if ( _usePrivilegedPort ) { _channel = bindToPrivilegedPort ( ) ; _channelFuture = _channel . connect ( getRemoteAddress ( ) ) ; } else { _channelFuture = _clientBootstrap . connect ( ) ; _channel = _channelFuture . getChannel ( ) ; } NioSocketChannelConfig cfg = ( NioSocketChannelConfig ) _channel . getConfig ( ) ; cfg . setWriteBufferHighWaterMark ( MAX_SENDING_QUEUE_SIZE ) ; _channelFuture . addListener ( new ChannelFutureListener ( ) { public void operationComplete ( ChannelFuture future ) { if ( _channelFuture . isSuccess ( ) ) { _state = State . CONNECTED ; oldChannelFuture . setSuccess ( ) ; } else { _state = State . DISCONNECTED ; oldChannelFuture . cancel ( ) ; } } } ) ; }
|
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 ( ) . newChannel ( pipeline ) ; channel . getConfig ( ) . setOptions ( _clientBootstrap . getOptions ( ) ) ; ChannelFuture bindFuture = channel . bind ( new InetSocketAddress ( port ) ) . awaitUninterruptibly ( ) ; if ( bindFuture . isSuccess ( ) ) { System . out . println ( "Success! Bound to port " + port ) ; return bindFuture . getChannel ( ) ; } } catch ( Exception e ) { String msg = String . format ( "rpc request bind error for address: %s" , getRemoteAddress ( ) ) ; throw new RpcException ( RpcStatus . NETWORK_ERROR , msg , e ) ; } } throw new RpcException ( RpcStatus . LOCAL_BINDING_ERROR , String . format ( "Cannot bind a port < 1024: %s" , getRemoteAddress ( ) ) ) ; }
|
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 = parentFile . getParentFile ( ) ; } else if ( ".." . equals ( name ) ) { parentFile = parentFile . getParentFile ( ) ; if ( parentFile == null ) { name = "" ; } else { name = parentFile . getName ( ) ; parentFile = parentFile . getParentFile ( ) ; } } } _parentFile = parentFile ; _name = name ; setPathFields ( ) ; }
|
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 the special cases have already been resolved for the parents and all supporting ancestors so those possibilities need only be considered at the current level eliminating any need for explicit recursive handling here .
|
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 ) { } } setFileHandle ( fileHandle ) ; }
|
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 ( ) ) { LOG . debug ( "server {}, port {}, response {}" , _server , _port , responseHandler . getResponse ( ) ) ; } responseHandler . checkResponse ( request ) ; }
|
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 ) ; Thread . sleep ( waitTime ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; } LOG . warn ( "network error happens, server {}, attemptNumber {}" , new Object [ ] { _server , attemptNumber } ) ; return ; } messageStart = "network" ; } throw new NfsException ( NfsStatus . NFS3ERR_IO , String . format ( "%s error, server: %s, RPC error: %s" , messageStart , _server , e . getMessage ( ) ) , e ) ; }
|
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 ( ) ; for ( String ip : ips ) { sb . append ( ip ) ; sb . append ( " " ) ; } LOG . debug ( sb . toString ( ) ) ; } return ( String [ ] ) ips . toArray ( new String [ 0 ] ) ; }
|
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 : _connectionMap ; Connection connection = connectionMap . get ( key ) ; if ( connection == null ) { connection = new Connection ( serverIP , port , usePrivilegedPort ) ; connectionMap . put ( key , connection ) ; connection . connect ( ) ; } return connection . sendAndWait ( timeout , xdrRequest ) ; }
|
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 = response . getBytesRead ( ) ; _offset += _bytesInBuffer ; _isEof = response . isEof ( ) ; } }
|
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 ) && ( ( attemptNumber + 1 ) < MOUNT_MAX_RETRIES ) ; if ( ! retry ) { String messageStart = networkError ? "network" : "rpc" ; String msg = String . format ( "%s error, server: %s, export: %s, RPC error: %s" , messageStart , _server , _exportedPath , e . getMessage ( ) ) ; throw new MountException ( MountStatus . MNT3ERR_IO , msg , e ) ; } System . out . println ( "retry " + ( attemptNumber + 1 ) ) ; if ( tryPrivilegedPort ) { LOG . info ( "Next try will be with a privileged port." ) ; } return tryPrivilegedPort ; }
|
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 = new NfsResponseHandler < Nfs3ReadResponse > ( ) { protected Nfs3ReadResponse makeNewResponse ( ) { return new Nfs3ReadResponse ( data , pos ) ; } public void checkResponse ( RpcRequest request ) throws IOException { super . checkResponse ( request ) ; eof . setValue ( getResponse ( ) . isEof ( ) ) ; } } ; _rpcWrapper . callRpcWrapped ( request , responseHandler ) ; return responseHandler . getResponse ( ) . getBytesRead ( ) ; }
|
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 : _unresolvedPaths ) { if ( path . equals ( unresolvedPath ) || path . startsWith ( unresolvedPath + "/" ) ) { throw new IOException ( "Links form a loop: " + path ) ; } } _unresolvedPaths . add ( path ) ; } return resolvedPath ; }
|
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 ; } MappingMetaData doc = mapping . mappings ( ) . values ( ) . iterator ( ) . next ( ) ; return ! doc . getSourceAsMap ( ) . isEmpty ( ) ; }
|
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 .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.