idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
27,100
private void copyInternal ( Map < FileInfo , URI > srcToDstItemNames ) throws IOException { if ( srcToDstItemNames . isEmpty ( ) ) { return ; } String srcBucketName = null ; String dstBucketName = null ; List < String > srcObjectNames = new ArrayList < > ( srcToDstItemNames . size ( ) ) ; List < String > dstObjectNames...
Copies items in given map that maps source items to destination items .
27,101
public List < URI > listFileNames ( FileInfo fileInfo , boolean recursive ) throws IOException { Preconditions . checkNotNull ( fileInfo ) ; URI path = fileInfo . getPath ( ) ; logger . atFine ( ) . log ( "listFileNames(%s)" , path ) ; List < URI > paths = new ArrayList < > ( ) ; List < String > childNames ; if ( fileI...
If the given item is a directory then the paths of its children are returned otherwise the path of the given item is returned .
27,102
public List < FileInfo > listFileInfo ( URI path ) throws IOException { Preconditions . checkNotNull ( path , "path can not be null" ) ; logger . atFine ( ) . log ( "listFileInfo(%s)" , path ) ; StorageResourceId pathId = pathCodec . validatePathAndGetId ( path , true ) ; StorageResourceId dirId = pathCodec . validateP...
If the given path points to a directory then the information about its children is returned otherwise information about the given file is returned .
27,103
public FileInfo getFileInfo ( URI path ) throws IOException { logger . atFine ( ) . log ( "getFileInfo(%s)" , path ) ; checkArgument ( path != null , "path must not be null" ) ; StorageResourceId resourceId = pathCodec . validatePathAndGetId ( path , true ) ; FileInfo fileInfo = FileInfo . fromItemInfo ( pathCodec , ge...
Gets information about the given path item .
27,104
public void close ( ) { if ( gcs != null ) { logger . atFine ( ) . log ( "close()" ) ; try { gcs . close ( ) ; } finally { gcs = null ; if ( updateTimestampsExecutor != null ) { try { shutdownExecutor ( updateTimestampsExecutor , 10 ) ; } finally { updateTimestampsExecutor = null ; } } if ( cachedExecutor != null ) { t...
Releases resources used by this instance .
27,105
public void mkdir ( URI path ) throws IOException { logger . atFine ( ) . log ( "mkdir(%s)" , path ) ; Preconditions . checkNotNull ( path ) ; checkArgument ( ! path . equals ( GCS_ROOT ) , "Cannot create root directory." ) ; StorageResourceId resourceId = pathCodec . validatePathAndGetId ( path , true ) ; if ( resourc...
Creates a directory at the specified path .
27,106
static String validateBucketName ( String bucketName ) { bucketName = FileInfo . convertToFilePath ( bucketName ) ; if ( Strings . isNullOrEmpty ( bucketName ) ) { throw new IllegalArgumentException ( "Google Cloud Storage bucket name cannot be empty." ) ; } if ( ! BUCKET_NAME_CHAR_MATCHER . matchesAllOf ( bucketName )...
Validate the given bucket name to make sure that it can be used as a part of a file system path .
27,107
static String validateObjectName ( String objectName , boolean allowEmptyObjectName ) { logger . atFine ( ) . log ( "validateObjectName('%s', %s)" , objectName , allowEmptyObjectName ) ; if ( isNullOrEmpty ( objectName ) || objectName . equals ( PATH_DELIMITER ) ) { if ( allowEmptyObjectName ) { objectName = "" ; } els...
Validate the given object name to make sure that it can be used as a part of a file system path .
27,108
String getItemName ( URI path ) { Preconditions . checkNotNull ( path ) ; if ( path . equals ( GCS_ROOT ) ) { return null ; } StorageResourceId resourceId = pathCodec . validatePathAndGetId ( path , true ) ; if ( resourceId . isBucket ( ) ) { return resourceId . getBucketName ( ) ; } int index ; String objectName = res...
Gets the leaf item of the given path .
27,109
public static StorageResourceId validatePathAndGetId ( URI uri , boolean allowEmptyObjectNames ) { return LEGACY_PATH_CODEC . validatePathAndGetId ( uri , allowEmptyObjectNames ) ; }
Validate a URI using the legacy path codec and return a StorageResourceId .
27,110
public static URI getParentPath ( PathCodec pathCodec , URI path ) { Preconditions . checkNotNull ( path ) ; if ( path . equals ( GCS_ROOT ) ) { return null ; } StorageResourceId resourceId = pathCodec . validatePathAndGetId ( path , true ) ; if ( resourceId . isBucket ( ) ) { return GCS_ROOT ; } int index ; String obj...
Gets the parent directory of the given path .
27,111
public void commitJob ( JobContext context ) throws IOException { super . commitJob ( context ) ; Configuration conf = context . getConfiguration ( ) ; TableReference destTable = BigQueryOutputConfiguration . getTableReference ( conf ) ; String destProjectId = BigQueryOutputConfiguration . getProjectId ( conf ) ; Optio...
Runs a federated import job on BigQuery for the data in the output path in addition to calling the delegate s commitJob .
27,112
protected void configureBuckets ( GoogleCloudStorageFileSystem gcsFs ) throws IOException { rootBucket = initUri . getAuthority ( ) ; checkArgument ( rootBucket != null , "No bucket specified in GCS URI: %s" , initUri ) ; pathCodec . getPath ( rootBucket , null , true ) ; logger . atFine ( ) . log ( "GHFS.configureBuck...
Sets and validates the root bucket .
27,113
public Path getHadoopPath ( URI gcsPath ) { logger . atFine ( ) . log ( "GHFS.getHadoopPath: %s" , gcsPath ) ; if ( gcsPath . equals ( getGcsPath ( getFileSystemRoot ( ) ) ) ) { return getFileSystemRoot ( ) ; } StorageResourceId resourceId = pathCodec . validatePathAndGetId ( gcsPath , true ) ; checkArgument ( ! resour...
Validates GCS Path belongs to this file system . The bucket must match the root bucket provided at initialization time .
27,114
private JsonBatchCallback < Void > getDeletionCallback ( final StorageResourceId resourceId , final KeySetView < IOException , Boolean > innerExceptions , final BatchHelper batchHelper , final int attempt , final long generation ) { return new JsonBatchCallback < Void > ( ) { public void onSuccess ( Void obj , HttpHead...
Helper to create a callback for a particular deletion request .
27,115
private void rewriteInternal ( final BatchHelper batchHelper , final KeySetView < IOException , Boolean > innerExceptions , final String srcBucketName , final String srcObjectName , final String dstBucketName , final String dstObjectName ) throws IOException { Storage . Objects . Rewrite rewriteObject = configureReques...
Performs copy operation using GCS Rewrite requests
27,116
private void copyInternal ( BatchHelper batchHelper , final KeySetView < IOException , Boolean > innerExceptions , final String srcBucketName , final String srcObjectName , final String dstBucketName , final String dstObjectName ) throws IOException { Storage . Objects . Copy copyObject = configureRequest ( gcs . objec...
Performs copy operation using GCS Copy requests
27,117
private void onCopyFailure ( KeySetView < IOException , Boolean > innerExceptions , GoogleJsonError e , String srcBucketName , String srcObjectName ) { if ( errorExtractor . itemNotFound ( e ) ) { FileNotFoundException fnfe = GoogleCloudStorageExceptions . getFileNotFoundException ( srcBucketName , srcObjectName ) ; in...
Processes failed copy requests
27,118
private void handlePrefixes ( String bucketName , List < String > prefixes , List < GoogleCloudStorageItemInfo > objectInfos ) { if ( storageOptions . isInferImplicitDirectoriesEnabled ( ) ) { for ( String prefix : prefixes ) { objectInfos . add ( GoogleCloudStorageItemInfo . createInferredDirectory ( new StorageResour...
Handle prefixes without prefix objects .
27,119
public static GoogleCloudStorageItemInfo createItemInfoForBucket ( StorageResourceId resourceId , Bucket bucket ) { Preconditions . checkArgument ( resourceId != null , "resourceId must not be null" ) ; Preconditions . checkArgument ( bucket != null , "bucket must not be null" ) ; Preconditions . checkArgument ( resour...
Helper for converting a StorageResourceId + Bucket into a GoogleCloudStorageItemInfo .
27,120
public static GoogleCloudStorageItemInfo createItemInfoForStorageObject ( StorageResourceId resourceId , StorageObject object ) { Preconditions . checkArgument ( resourceId != null , "resourceId must not be null" ) ; Preconditions . checkArgument ( object != null , "object must not be null" ) ; Preconditions . checkArg...
Helper for converting a StorageResourceId + StorageObject into a GoogleCloudStorageItemInfo .
27,121
private Bucket getBucket ( String bucketName ) throws IOException { logger . atFine ( ) . log ( "getBucket(%s)" , bucketName ) ; checkArgument ( ! Strings . isNullOrEmpty ( bucketName ) , "bucketName must not be null or empty" ) ; Storage . Buckets . Get getBucket = configureRequest ( gcs . buckets ( ) . get ( bucketNa...
Gets the bucket with the given name .
27,122
private long getWriteGeneration ( StorageResourceId resourceId , boolean overwritable ) throws IOException { logger . atFine ( ) . log ( "getWriteGeneration(%s, %s)" , resourceId , overwritable ) ; GoogleCloudStorageItemInfo info = getItemInfo ( resourceId ) ; if ( ! info . exists ( ) ) { return 0L ; } if ( info . exis...
Gets the object generation for a Write operation
27,123
private StorageObject getObject ( StorageResourceId resourceId ) throws IOException { logger . atFine ( ) . log ( "getObject(%s)" , resourceId ) ; Preconditions . checkArgument ( resourceId . isStorageObject ( ) , "Expected full StorageObject id, got %s" , resourceId ) ; String bucketName = resourceId . getBucketName (...
Gets the object with the given resourceId .
27,124
private static synchronized HttpTransport getStaticHttpTransport ( ) throws IOException , GeneralSecurityException { if ( staticHttpTransport == null ) { staticHttpTransport = HttpTransportFactory . createHttpTransport ( HttpTransportType . JAVA_NET ) ; } return staticHttpTransport ; }
Returns shared staticHttpTransport instance ; initializes staticHttpTransport if it hasn t already been initialized .
27,125
public Credential getCredentialFromJsonKeyFile ( String serviceAccountJsonKeyFile , List < String > scopes , HttpTransport transport ) throws IOException , GeneralSecurityException { logger . atFine ( ) . log ( "getCredentialFromJsonKeyFile(%s, %s)" , serviceAccountJsonKeyFile , scopes ) ; try ( FileInputStream fis = n...
Get credentials listed in a JSON file .
27,126
public boolean nextKeyValue ( ) throws IOException , InterruptedException { currentValue = null ; if ( delegateReader != null ) { if ( delegateReader . nextKeyValue ( ) ) { populateCurrentKeyValue ( ) ; return true ; } else { delegateReader . close ( ) ; delegateReader = null ; } } boolean needRefresh = ! isNextFileRea...
Reads the next key value pair . Gets next line and parses Json object . May hang for a long time waiting for more files to appear in this reader s directory .
27,127
public void close ( ) throws IOException { if ( delegateReader != null ) { logger . atWarning ( ) . log ( "Got non-null delegateReader during close(); possible premature close() call." ) ; delegateReader . close ( ) ; delegateReader = null ; } }
Closes the record reader .
27,128
private void setEndFileMarkerFile ( String fileName ) { int fileIndex = parseFileIndex ( fileName ) ; if ( endFileNumber == - 1 ) { endFileNumber = fileIndex ; logger . atInfo ( ) . log ( "Found end-marker file '%s' with index %s" , fileName , endFileNumber ) ; for ( String knownFile : knownFileSet ) { int knownFileInd...
Record a specific file as being the 0 - record end of stream marker .
27,129
private void refreshFileList ( ) throws IOException { FileStatus [ ] files = fileSystem . globStatus ( inputDirectoryAndPattern ) ; for ( FileStatus file : files ) { String fileName = file . getPath ( ) . getName ( ) ; if ( ! knownFileSet . contains ( fileName ) ) { if ( endFileNumber != - 1 ) { int newFileIndex = pars...
Lists files and sifts through the results for any new files we haven t found before . If a file of size 0 is found we mark the endFileNumber from it .
27,130
public void bindToAnyDelegationToken ( ) throws IOException { validateAccessTokenProvider ( ) ; Token < DelegationTokenIdentifier > token = selectTokenFromFsOwner ( ) ; if ( token != null ) { bindToDelegationToken ( token ) ; } else { deployUnbonded ( ) ; } if ( accessTokenProvider == null ) { throw new DelegationToken...
Attempt to bind to any existing DT including unmarshalling its contents and creating the GCP credential provider used to authenticate the client .
27,131
public Token < DelegationTokenIdentifier > selectTokenFromFsOwner ( ) throws IOException { return lookupToken ( user . getCredentials ( ) , service , tokenBinding . getKind ( ) ) ; }
Find a token for the FS user and service name .
27,132
public void bindToDelegationToken ( Token < DelegationTokenIdentifier > token ) throws IOException { validateAccessTokenProvider ( ) ; boundDT = token ; DelegationTokenIdentifier dti = extractIdentifier ( token ) ; logger . atInfo ( ) . log ( "Using delegation token %s" , dti ) ; accessTokenProvider = tokenBinding . bi...
Bind to a delegation token retrieved for this filesystem . Extract the secrets from the token and set internal fields to the values .
27,133
@ SuppressWarnings ( "OptionalGetWithoutIsPresent" ) public Token < DelegationTokenIdentifier > getBoundOrNewDT ( String renewer ) throws IOException { logger . atFine ( ) . log ( "Delegation token requested" ) ; if ( isBoundToDT ( ) ) { logger . atFine ( ) . log ( "Returning current token" ) ; return getBoundDT ( ) ; ...
Get any bound DT or create a new one .
27,134
public static DelegationTokenIdentifier extractIdentifier ( final Token < ? extends DelegationTokenIdentifier > token ) throws IOException { checkArgument ( token != null , "null token" ) ; DelegationTokenIdentifier identifier ; try { identifier = token . decodeIdentifier ( ) ; } catch ( RuntimeException e ) { Throwabl...
From a token get the session token identifier .
27,135
@ SuppressWarnings ( "unchecked" ) private static Token < DelegationTokenIdentifier > lookupToken ( Credentials credentials , Text service , Text kind ) throws DelegationTokenIOException { logger . atFine ( ) . log ( "Looking for token for service %s in credentials" , service ) ; Token < ? > token = credentials . getTo...
Look up a token from the credentials verify it is of the correct kind .
27,136
public static String getMandatoryConfig ( Configuration config , String key ) throws IOException { String value = config . get ( key ) ; if ( Strings . isNullOrEmpty ( value ) ) { throw new IOException ( "Must supply a value for configuration setting: " + key ) ; } return value ; }
Gets value for the given key or throws if value is not found .
27,137
public static Map < String , String > getMandatoryConfig ( Configuration config , List < String > keys ) throws IOException { List < String > missingKeys = new ArrayList < > ( ) ; Map < String , String > values = new HashMap < > ( ) ; for ( String key : keys ) { String value = config . get ( key ) ; if ( Strings . isNu...
Gets value for the given keys or throws if one or more values are not found .
27,138
public void setUploadChunkSize ( int chunkSize ) { Preconditions . checkArgument ( chunkSize > 0 , "Upload chunk size must be great than 0." ) ; Preconditions . checkArgument ( chunkSize % MediaHttpUploader . MINIMUM_CHUNK_SIZE == 0 , "Upload chunk size must be a multiple of MediaHttpUploader.MINIMUM_CHUNK_SIZE" ) ; if...
Sets size of upload buffer used .
27,139
public synchronized int write ( ByteBuffer buffer ) throws IOException { checkState ( isInitialized , "initialize() must be invoked before use." ) ; if ( ! isOpen ( ) ) { throw new ClosedChannelException ( ) ; } if ( uploadOperation . isDone ( ) ) { waitForCompletionAndThrowIfUploadFailed ( ) ; } return pipeSinkChannel...
Writes contents of the given buffer to this channel .
27,140
public void initialize ( ) throws IOException { PipedInputStream pipeSource = new PipedInputStream ( pipeBufferSize ) ; OutputStream pipeSink = new PipedOutputStream ( pipeSource ) ; pipeSinkChannel = Channels . newChannel ( pipeSink ) ; InputStreamContent objectContentStream = new InputStreamContent ( contentType , pi...
Initialize this channel object for writing .
27,141
private S waitForCompletionAndThrowIfUploadFailed ( ) throws IOException { try { return uploadOperation . get ( ) ; } catch ( InterruptedException e ) { uploadOperation . cancel ( true ) ; IOException exception = new ClosedByInterruptException ( ) ; exception . addSuppressed ( e ) ; throw exception ; } catch ( Executio...
Throws if upload operation failed . Propagates any errors .
27,142
public static FileNotFoundException getFileNotFoundException ( String bucketName , String objectName ) { checkArgument ( ! isNullOrEmpty ( bucketName ) , "bucketName must not be null or empty" ) ; return new FileNotFoundException ( String . format ( "Item not found: '%s'." + " If you enabled STRICT generation consisten...
Creates FileNotFoundException with suitable message for a GCS bucket or object .
27,143
@ SuppressWarnings ( "unchecked" ) public static < T , X extends Exception > T retry ( CheckedCallable < T , X > callable , BackOff backoff , RetryDeterminer < ? super X > retryDet , Class < X > classType , Sleeper sleeper ) throws X , InterruptedException { checkNotNull ( backoff , "Must provide a non-null BackOff." )...
Retries the given executable function in the case of transient errors defined by the RetryDeterminer .
27,144
public static < T , X extends Exception > T retry ( CheckedCallable < T , X > callable , BackOff backoff , RetryDeterminer < ? super X > retryDet , Class < X > classType ) throws X , InterruptedException { return retry ( callable , backoff , retryDet , classType , Sleeper . DEFAULT ) ; }
Retries the given executable function in the case of transient errors defined by the RetryDeterminer and uses default sleeper .
27,145
private static boolean nextSleep ( BackOff backoff , Sleeper sleeper , Exception currentException ) throws InterruptedException { long backOffTime ; try { backOffTime = backoff . nextBackOffMillis ( ) ; } catch ( IOException e ) { throw new RuntimeException ( "Failed to to get next back off time" , e ) ; } if ( backOff...
Determines the amount to sleep for and sleeps if needed .
27,146
static boolean objectHasDirectoryPath ( String objectName ) { return ! Strings . isNullOrEmpty ( objectName ) && objectName . endsWith ( GoogleCloudStorage . PATH_DELIMITER ) ; }
Indicates whether the given object name looks like a directory path .
27,147
private void flushIfPossible ( boolean flushAll ) throws IOException { if ( flushAll ) { flushLock . lock ( ) ; } else if ( pendingRequests . isEmpty ( ) || ! flushLock . tryLock ( ) ) { return ; } try { do { flushPendingRequests ( ) ; if ( flushAll ) { awaitRequestsCompletion ( ) ; } } while ( flushAll && ( ! pendingR...
Flush our buffer if we are not already in a flush operation and we have data to flush .
27,148
public void flush ( ) throws IOException { try { flushIfPossible ( true ) ; checkState ( pendingRequests . isEmpty ( ) , "pendingRequests should be empty after flush" ) ; checkState ( responseFutures . isEmpty ( ) , "responseFutures should be empty after flush" ) ; } finally { requestsExecutor . shutdown ( ) ; try { if...
Sends any currently remaining requests in the batch ; should be called at the end of any series of batched requests to ensure everything has been sent .
27,149
private void awaitRequestsCompletion ( ) throws IOException { while ( ! responseFutures . isEmpty ( ) && pendingRequests . size ( ) < maxRequestsPerBatch ) { try { responseFutures . remove ( ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { if ( e . getCause ( ) instanceof IOException ) { throw ( ...
Awaits until all sent requests are completed . Should be serialized
27,150
public synchronized GoogleCloudStorageItemInfo putItem ( GoogleCloudStorageItemInfo item ) { StorageResourceId id = item . getResourceId ( ) ; PrefixKey key = new PrefixKey ( id . getBucketName ( ) , id . getObjectName ( ) ) ; CacheValue < GoogleCloudStorageItemInfo > value = new CacheValue < GoogleCloudStorageItemInfo...
Inserts an item into the cache . If an item with the same resource id is present it is overwritten by the new item .
27,151
public synchronized GoogleCloudStorageItemInfo removeItem ( StorageResourceId id ) { PrefixKey key = new PrefixKey ( id . getBucketName ( ) , id . getObjectName ( ) ) ; CacheValue < GoogleCloudStorageItemInfo > value = itemMap . remove ( key ) ; if ( value == null ) { return null ; } if ( isExpired ( value ) ) { cleanu...
Removes the item from the cache . If the item has expired associated lists are invalidated .
27,152
public synchronized void invalidateBucket ( String bucket ) { PrefixKey key = new PrefixKey ( bucket , "" ) ; getPrefixSubMap ( itemMap , key ) . clear ( ) ; getPrefixSubMap ( prefixMap , key ) . clear ( ) ; }
Invalidates all cached items and lists associated with the given bucket .
27,153
private void cleanupLists ( PrefixKey key ) { NavigableMap < PrefixKey , CacheValue < Object > > head = prefixMap . headMap ( key , true ) . descendingMap ( ) ; Iterator < Entry < PrefixKey , CacheValue < Object > > > headItr = head . entrySet ( ) . iterator ( ) ; Entry < PrefixKey , CacheValue < Object > > last = null...
Removes expired list entries that contain the given key . If a list was removed it s contained items are checked for expiration too .
27,154
private static < K , V > List < V > aggregateCacheValues ( Map < K , CacheValue < V > > map ) { List < V > values = new ArrayList < > ( map . size ( ) ) ; for ( Map . Entry < K , CacheValue < V > > entry : map . entrySet ( ) ) { values . add ( entry . getValue ( ) . getValue ( ) ) ; } return values ; }
Extracts all the cached values in a map .
27,155
public Token < ? > addDelegationTokens ( Configuration conf , Credentials creds , String renewer , String url ) throws Exception { if ( ! url . startsWith ( SCHEME ) ) { url = SCHEME + "://" + url ; } FileSystem fs = FileSystem . get ( URI . create ( url ) , conf ) ; Token < ? > token = fs . getDelegationToken ( renewe...
Returns Token object via FileSystem null if bad argument .
27,156
public static Credential credential ( AccessTokenProviderClassFromConfigFactory providerClassFactory , Configuration config , Collection < String > scopes ) throws IOException , GeneralSecurityException { Class < ? extends AccessTokenProvider > clazz = providerClassFactory . getAccessTokenProviderClass ( config ) ; if ...
Generate the credential .
27,157
public Credential createBigQueryCredential ( Configuration config ) throws GeneralSecurityException , IOException { Credential credential = CredentialFromAccessTokenProviderClassFactory . credential ( new AccessTokenProviderClassFromConfigFactory ( ) . withOverridePrefix ( "mapred.bq" ) , config , BIGQUERY_OAUTH_SCOPES...
Construct credentials from the passed Configuration .
27,158
public Bigquery getBigQuery ( Configuration config ) throws GeneralSecurityException , IOException { logger . atInfo ( ) . log ( "Creating BigQuery from default credential." ) ; Credential credential = createBigQueryCredential ( config ) ; return getBigQueryFromCredential ( credential , BQC_ID ) ; }
Constructs a BigQuery from the credential constructed from the environment .
27,159
public Bigquery getBigQueryFromCredential ( Credential credential , String appName ) { logger . atInfo ( ) . log ( "Creating BigQuery from given credential." ) ; if ( credential != null ) { return new Bigquery . Builder ( HTTP_TRANSPORT , JSON_FACTORY , new RetryHttpInitializer ( credential , appName ) ) . setApplicati...
Constructs a BigQuery from a given Credential .
27,160
public static void waitForJobCompletion ( Bigquery bigquery , String projectId , JobReference jobReference , Progressable progressable ) throws IOException , InterruptedException { Sleeper sleeper = Sleeper . DEFAULT ; BackOff pollBackOff = new ExponentialBackOff . Builder ( ) . setMaxIntervalMillis ( POLL_WAIT_INTERVA...
Polls job until it is completed .
27,161
public static List < TableFieldSchema > getSchemaFromString ( String fields ) { logger . atFine ( ) . log ( "getSchemaFromString('%s')" , fields ) ; JsonParser jsonParser = new JsonParser ( ) ; JsonArray json = jsonParser . parse ( fields ) . getAsJsonArray ( ) ; List < TableFieldSchema > fieldsList = new ArrayList < >...
Parses the given JSON string and returns the extracted schema .
27,162
public void initialize ( URI path , Configuration config , boolean initSuperclass ) throws IOException { long startTime = System . nanoTime ( ) ; Preconditions . checkArgument ( path != null , "path must not be null" ) ; Preconditions . checkArgument ( config != null , "config must not be null" ) ; Preconditions . chec...
Initializes this file system instance .
27,163
private void initializeDelegationTokenSupport ( Configuration config , URI path ) throws IOException { logger . atFine ( ) . log ( "GHFS.initializeDelegationTokenSupport" ) ; GcsDelegationTokens dts = new GcsDelegationTokens ( ) ; Text service = new Text ( getScheme ( ) + "://" + path . getAuthority ( ) ) ; dts . bindT...
Initialize the delegation token support for this filesystem .
27,164
protected int getDefaultPort ( ) { logger . atFine ( ) . log ( "GHFS.getDefaultPort:" ) ; int result = - 1 ; logger . atFine ( ) . log ( "GHFS.getDefaultPort:=> %s" , result ) ; return result ; }
The default port is listed as - 1 as an indication that ports are not used .
27,165
public FSDataOutputStream create ( Path hadoopPath , FsPermission permission , boolean overwrite , int bufferSize , short replication , long blockSize , Progressable progress ) throws IOException { long startTime = System . nanoTime ( ) ; Preconditions . checkArgument ( hadoopPath != null , "hadoopPath must not be null...
Opens the given file for writing .
27,166
public void concat ( Path trg , Path [ ] psrcs ) throws IOException { logger . atFine ( ) . log ( "GHFS.concat: %s, %s" , trg , lazy ( ( ) -> Arrays . toString ( psrcs ) ) ) ; checkArgument ( psrcs . length > 0 , "psrcs must have at least one source" ) ; URI trgPath = getGcsPath ( trg ) ; List < URI > srcPaths = Arrays...
Concat existing files into one file .
27,167
public boolean rename ( Path src , Path dst ) throws IOException { if ( src . makeQualified ( this ) . equals ( getFileSystemRoot ( ) ) ) { logger . atFine ( ) . log ( "GHFS.rename: src is root: '%s'" , src ) ; return false ; } long startTime = System . nanoTime ( ) ; Preconditions . checkArgument ( src != null , "src ...
Renames src to dst . Src must not be equal to the filesystem root .
27,168
public FileStatus [ ] listStatus ( Path hadoopPath ) throws IOException { long startTime = System . nanoTime ( ) ; Preconditions . checkArgument ( hadoopPath != null , "hadoopPath must not be null" ) ; checkOpen ( ) ; logger . atFine ( ) . log ( "GHFS.listStatus: %s" , hadoopPath ) ; URI gcsPath = getGcsPath ( hadoopPa...
Lists file status . If the given path points to a directory then the status of children is returned otherwise the status of the given file is returned .
27,169
public void setWorkingDirectory ( Path hadoopPath ) { long startTime = System . nanoTime ( ) ; Preconditions . checkArgument ( hadoopPath != null , "hadoopPath must not be null" ) ; logger . atFine ( ) . log ( "GHFS.setWorkingDirectory: %s" , hadoopPath ) ; URI gcsPath = FileInfo . convertToDirectoryPath ( pathCodec , ...
Sets the current working directory to the given path .
27,170
public boolean mkdirs ( Path hadoopPath , FsPermission permission ) throws IOException { long startTime = System . nanoTime ( ) ; Preconditions . checkArgument ( hadoopPath != null , "hadoopPath must not be null" ) ; checkOpen ( ) ; logger . atFine ( ) . log ( "GHFS.mkdirs: %s, perm: %s" , hadoopPath , permission ) ; U...
Makes the given path and all non - existent parents directories . Has the semantics of Unix mkdir - p .
27,171
public FileStatus getFileStatus ( Path hadoopPath ) throws IOException { long startTime = System . nanoTime ( ) ; Preconditions . checkArgument ( hadoopPath != null , "hadoopPath must not be null" ) ; checkOpen ( ) ; logger . atFine ( ) . log ( "GHFS.getFileStatus: %s" , hadoopPath ) ; URI gcsPath = getGcsPath ( hadoop...
Gets status of the given path item .
27,172
private FileStatus getFileStatus ( FileInfo fileInfo , String userName ) throws IOException { FileStatus status = new FileStatus ( fileInfo . getSize ( ) , fileInfo . isDirectory ( ) , REPLICATION_FACTOR_DEFAULT , defaultBlockSize , fileInfo . getModificationTime ( ) , fileInfo . getModificationTime ( ) , reportedPermi...
Gets FileStatus corresponding to the given FileInfo value .
27,173
public FileStatus [ ] globStatus ( Path pathPattern , PathFilter filter ) throws IOException { checkOpen ( ) ; logger . atFine ( ) . log ( "GHFS.globStatus: %s" , pathPattern ) ; Path encodedPath = new Path ( pathPattern . toUri ( ) . toString ( ) ) ; Path encodedFixedPath = getHadoopPath ( getGcsPath ( encodedPath ) )...
Returns an array of FileStatus objects whose path names match pathPattern and is accepted by the user - supplied path filter . Results are sorted by their path names .
27,174
private FileStatus [ ] concurrentGlobInternal ( Path fixedPath , PathFilter filter ) throws IOException { ExecutorService executorService = Executors . newFixedThreadPool ( 2 , DAEMON_THREAD_FACTORY ) ; Callable < FileStatus [ ] > flatGlobTask = ( ) -> flatGlobInternal ( fixedPath , filter ) ; Callable < FileStatus [ ]...
Use 2 glob algorithms that return the same result but one of them could be significantly faster than another one depending on directory layout .
27,175
public Path getHomeDirectory ( ) { Path result = new Path ( getFileSystemRoot ( ) , getHomeDirectorySubpath ( ) ) ; logger . atFine ( ) . log ( "GHFS.getHomeDirectory:=> %s" , result ) ; return result ; }
Returns home directory of the current user .
27,176
private static String fileStatusToString ( FileStatus stat ) { assert stat != null ; return String . format ( "path: %s, isDir: %s, len: %d, owner: %s" , stat . getPath ( ) . toString ( ) , stat . isDir ( ) , stat . getLen ( ) , stat . getOwner ( ) ) ; }
Converts the given FileStatus to its string representation .
27,177
private static void copyIfNotPresent ( Configuration config , String deprecatedKey , String newKey ) { String deprecatedValue = config . get ( deprecatedKey ) ; if ( config . get ( newKey ) == null && deprecatedValue != null ) { logger . atWarning ( ) . log ( "Key %s is deprecated. Copying the value of key %s to new ke...
Copy the value of the deprecated key to the new key if a value is present for the deprecated key but not the new key .
27,178
private static void copyDeprecatedConfigurationOptions ( Configuration config ) { copyIfNotPresent ( config , GoogleHadoopFileSystemConfiguration . AUTH_SERVICE_ACCOUNT_ENABLE . getKey ( ) , AUTHENTICATION_PREFIX + HadoopCredentialConfiguration . ENABLE_SERVICE_ACCOUNTS_SUFFIX ) ; copyIfNotPresent ( config , GoogleHado...
Copy deprecated configuration options to new keys if present .
27,179
private synchronized void configure ( Configuration config ) throws IOException { logger . atFine ( ) . log ( "GHFS.configure" ) ; logger . atFine ( ) . log ( "GHFS_ID = %s" , GHFS_ID ) ; overrideConfigFromFile ( config ) ; copyDeprecatedConfigurationOptions ( config ) ; setConf ( config ) ; enableFlatGlob = GCS_FLAT_G...
Configures GHFS using the supplied configuration .
27,180
public static String matchListPrefix ( String objectNamePrefix , String delimiter , String objectName ) { Preconditions . checkArgument ( ! Strings . isNullOrEmpty ( objectName ) , "objectName must not be null or empty, had args %s/%s/%s: " , objectNamePrefix , delimiter , objectName ) ; String suffix = objectName ; in...
Helper that mimics the GCS API behavior for taking an existing objectName and checking if it matches a user - supplied prefix with an optional directory delimiter . If it matches either the full objectName will be returned unmodified or the return value will be a String that is a prefix of the objectName inclusive of t...
27,181
public SeekableByteChannel position ( long newPosition ) throws IOException { throwIfNotOpen ( ) ; if ( newPosition == currentPosition ) { return this ; } validatePosition ( newPosition ) ; logger . atFine ( ) . log ( "Seek from %s to %s position for '%s'" , currentPosition , newPosition , resourceIdString ) ; currentP...
Sets this channel s position .
27,182
protected void validatePosition ( long position ) throws IOException { if ( position < 0 ) { throw new EOFException ( String . format ( "Invalid seek offset: position value (%d) must be >= 0 for '%s'" , position , resourceIdString ) ) ; } if ( size >= 0 && position >= size ) { throw new EOFException ( String . format (...
Validates that the given position is valid for this channel .
27,183
public void write ( byte [ ] b , int offset , int len ) throws IOException { long startTime = System . nanoTime ( ) ; out . write ( b , offset , len ) ; statistics . incrementBytesWritten ( len ) ; long duration = System . nanoTime ( ) - startTime ; ghfs . increment ( GoogleHadoopFileSystemBase . Counter . WRITE ) ; gh...
Writes to this output stream len bytes of the specified buffer starting at the given offset .
27,184
public static void addModificationTimeToAttributes ( Map < String , byte [ ] > attributes , Clock clock ) { attributes . put ( FILE_MODIFICATION_TIMESTAMP_KEY , Longs . toByteArray ( clock . currentTimeMillis ( ) ) ) ; }
Add a key and value representing the current time as determined by the passed clock to the passed attributes dictionary .
27,185
public static String convertToFilePath ( String objectName ) { if ( ! Strings . isNullOrEmpty ( objectName ) ) { if ( objectHasDirectoryPath ( objectName ) ) { objectName = objectName . substring ( 0 , objectName . length ( ) - 1 ) ; } } return objectName ; }
Converts the given object name to look like a file path . If the object name already looks like a file path then this call is a no - op .
27,186
public static FileInfo fromItemInfo ( PathCodec pathCodec , GoogleCloudStorageItemInfo itemInfo ) { if ( itemInfo . isRoot ( ) ) { return ROOT_INFO ; } URI path = pathCodec . getPath ( itemInfo . getBucketName ( ) , itemInfo . getObjectName ( ) , true ) ; return new FileInfo ( path , itemInfo ) ; }
Handy factory method for constructing a FileInfo from a GoogleCloudStorageItemInfo while potentially returning a singleton instead of really constructing an object for cases like ROOT .
27,187
public static List < FileInfo > fromItemInfos ( PathCodec pathCodec , List < GoogleCloudStorageItemInfo > itemInfos ) { List < FileInfo > fileInfos = new ArrayList < > ( itemInfos . size ( ) ) ; for ( GoogleCloudStorageItemInfo itemInfo : itemInfos ) { fileInfos . add ( fromItemInfo ( pathCodec , itemInfo ) ) ; } retur...
Handy factory method for constructing a list of FileInfo from a list of GoogleCloudStorageItemInfo .
27,188
public static boolean isDirectoryPath ( URI path ) { return ( path != null ) && path . toString ( ) . endsWith ( GoogleCloudStorage . PATH_DELIMITER ) ; }
Indicates whether the given path looks like a directory path .
27,189
public static StorageResourceId convertToDirectoryPath ( StorageResourceId resourceId ) { if ( resourceId . isStorageObject ( ) ) { if ( ! objectHasDirectoryPath ( resourceId . getObjectName ( ) ) ) { resourceId = new StorageResourceId ( resourceId . getBucketName ( ) , convertToDirectoryPath ( resourceId . getObjectNa...
Converts the given resourceId to look like a directory path . If the path already looks like a directory path then this call is a no - op .
27,190
public static URI convertToDirectoryPath ( PathCodec pathCodec , URI path ) { StorageResourceId resourceId = pathCodec . validatePathAndGetId ( path , true ) ; if ( resourceId . isStorageObject ( ) ) { if ( ! objectHasDirectoryPath ( resourceId . getObjectName ( ) ) ) { resourceId = convertToDirectoryPath ( resourceId ...
Converts the given path to look like a directory path . If the path already looks like a directory path then this call is a no - op .
27,191
static String getTableFieldsJson ( TableSchema tableSchema ) throws IOException { return JacksonFactory . getDefaultInstance ( ) . toString ( tableSchema . getFields ( ) ) ; }
Gets the JSON representation of the table s fields .
27,192
public void initialize ( InputSplit genericSplit , TaskAttemptContext context ) throws IOException { if ( logger . atFine ( ) . isEnabled ( ) ) { try { logger . atFine ( ) . log ( "initialize('%s', '%s')" , HadoopToStringUtil . toString ( genericSplit ) , HadoopToStringUtil . toString ( context ) ) ; } catch ( Interrup...
Called once at initialization to initialize the RecordReader .
27,193
public boolean nextKeyValue ( ) throws IOException { if ( ! lineReader . nextKeyValue ( ) ) { logger . atFine ( ) . log ( "All values read: record reader read %s key, value pairs." , count ) ; return false ; } currentKey . set ( lineReader . getCurrentKey ( ) . get ( ) ) ; Text lineValue = lineReader . getCurrentValue ...
Reads the next key value pair . Gets next line and parses Json object .
27,194
public static GoogleCloudStorageItemInfo createInferredDirectory ( StorageResourceId resourceId ) { checkArgument ( resourceId != null , "resourceId must not be null" ) ; return new GoogleCloudStorageItemInfo ( resourceId , 0 , 0 , null , null ) ; }
Helper for creating a found GoogleCloudStorageItemInfo for an inferred directory .
27,195
public static GoogleCloudStorageItemInfo createNotFound ( StorageResourceId resourceId ) { checkArgument ( resourceId != null , "resourceId must not be null" ) ; return new GoogleCloudStorageItemInfo ( resourceId , 0 , - 1 , null , null ) ; }
Helper for creating a not found GoogleCloudStorageItemInfo for a StorageResourceId .
27,196
public void checkOutputSpecs ( JobContext job ) throws FileAlreadyExistsException , IOException { Configuration conf = job . getConfiguration ( ) ; BigQueryOutputConfiguration . validateConfiguration ( conf ) ; Path outputPath = BigQueryOutputConfiguration . getGcsOutputPath ( conf ) ; logger . atInfo ( ) . log ( "Usin...
Checks to make sure the configuration is valid the output path doesn t already exist and that a connection to BigQuery can be established .
27,197
public synchronized OutputCommitter getOutputCommitter ( TaskAttemptContext context ) throws IOException { if ( committer == null ) { committer = createCommitter ( context ) ; } return committer ; }
Gets the cached OutputCommitter creating a new one if it doesn t exist .
27,198
public RecordWriter < K , V > getRecordWriter ( TaskAttemptContext context ) throws IOException , InterruptedException { Configuration conf = context . getConfiguration ( ) ; return getDelegate ( conf ) . getRecordWriter ( context ) ; }
Gets the RecordWriter from the wrapped FileOutputFormat .
27,199
protected OutputCommitter createCommitter ( TaskAttemptContext context ) throws IOException { Configuration conf = context . getConfiguration ( ) ; return getDelegate ( conf ) . getOutputCommitter ( context ) ; }
Create a new OutputCommitter for this OutputFormat .