Class GoogleCloudStorageReadChannel
- java.lang.Object
-
- com.google.cloud.hadoop.gcsio.GoogleCloudStorageReadChannel
-
- All Implemented Interfaces:
Closeable,AutoCloseable,ByteChannel,Channel,ReadableByteChannel,SeekableByteChannel,WritableByteChannel
- Direct Known Subclasses:
InMemoryObjectReadChannel
public class GoogleCloudStorageReadChannel extends Object implements SeekableByteChannel
Provides seekable read access to GCS.
-
-
Field Summary
Fields Modifier and Type Field Description protected longcontentChannelPositionprotected longcurrentPositionprotected booleanmetadataInitialized
-
Constructor Summary
Constructors Constructor Description GoogleCloudStorageReadChannel(com.google.api.services.storage.Storage gcs, StorageResourceId resourceId, ApiErrorExtractor errorExtractor, ClientRequestHelper<com.google.api.services.storage.model.StorageObject> requestHelper, GoogleCloudStorageReadOptions readOptions)Constructs an instance of GoogleCloudStorageReadChannel.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()Closes this channel.protected voidcloseContentChannel()Closes the underlyingReadableByteChannel.protected com.google.api.services.storage.Storage.Objects.GetcreateDataRequest()protected com.google.api.services.storage.Storage.Objects.GetcreateMetadataRequest()protected GoogleCloudStorageItemInfogetInitialMetadata()ReturnsGoogleCloudStorageItemInfoused to initialize metadata in constructor ornullifGoogleCloudStorageReadOptions.isFastFailOnNotFoundEnabled()is set tofalse.protected voidinitMetadata(com.google.api.client.http.HttpHeaders headers)Initializes metadata (size, encoding, etc) from HTTPheaders.protected voidinitMetadata(String encoding, long sizeFromMetadata, long generation)Initializes metadata (size, encoding, etc) from passed parameters.booleanisOpen()Tells whether this channel is open.protected InputStreamopenStream(long bytesToRead)Opens the underlying stream, sets its position to thecurrentPosition.longposition()Returns this channel's current position.SeekableByteChannelposition(long newPosition)Sets this channel's position.intread(ByteBuffer buffer)Reads from this channel and stores read data in the given buffer.voidsetMaxRetries(int maxRetries)Sets the number of times to automatically retry by re-opening the underlying contentChannel whenever an exception occurs while reading from it.protected voidsetSize(long size)Sets size of this channel to the given value.longsize()Returns size of the object to which this channel is connected.SeekableByteChanneltruncate(long size)protected voidvalidatePosition(long position)Validates that the given position is valid for this channel.intwrite(ByteBuffer src)
-
-
-
Constructor Detail
-
GoogleCloudStorageReadChannel
public GoogleCloudStorageReadChannel(com.google.api.services.storage.Storage gcs, StorageResourceId resourceId, ApiErrorExtractor errorExtractor, ClientRequestHelper<com.google.api.services.storage.model.StorageObject> requestHelper, @Nonnull GoogleCloudStorageReadOptions readOptions) throws IOExceptionConstructs an instance of GoogleCloudStorageReadChannel.- Parameters:
gcs- storage object instanceresourceId- contains information about a specific resourcerequestHelper- a ClientRequestHelper used to set any extra headersreadOptions- fine-grained options specifying things like retry settings, buffering, etc. Could not be null.- Throws:
IOException- on IO error
-
-
Method Detail
-
getInitialMetadata
@Nullable protected GoogleCloudStorageItemInfo getInitialMetadata() throws IOException
ReturnsGoogleCloudStorageItemInfoused to initialize metadata in constructor ornullifGoogleCloudStorageReadOptions.isFastFailOnNotFoundEnabled()is set tofalse.- Throws:
IOException
-
setMaxRetries
public void setMaxRetries(int maxRetries)
Sets the number of times to automatically retry by re-opening the underlying contentChannel whenever an exception occurs while reading from it. The count of attempted retries is reset whenever at least one byte is successfully read, so this number of retries refers to retries made without achieving any forward progress.
-
read
public int read(ByteBuffer buffer) throws IOException
Reads from this channel and stores read data in the given buffer.On unexpected failure, will attempt to close the channel and clean up state.
- Specified by:
readin interfaceReadableByteChannel- Specified by:
readin interfaceSeekableByteChannel- Parameters:
buffer- buffer to read data into- Returns:
- number of bytes read or -1 on end-of-stream
- Throws:
IOException- on IO error
-
truncate
public SeekableByteChannel truncate(long size)
- Specified by:
truncatein interfaceSeekableByteChannel
-
write
public int write(ByteBuffer src)
- Specified by:
writein interfaceSeekableByteChannel- Specified by:
writein interfaceWritableByteChannel
-
isOpen
public boolean isOpen()
Tells whether this channel is open.
-
closeContentChannel
protected void closeContentChannel()
Closes the underlyingReadableByteChannel.Catches and ignores all exceptions as there is not a lot the user can do to fix errors here and a new connection will be needed. Especially SSLExceptions since the there's a high probability that SSL connections would be broken in a way that causes
Channel.close()itself to throw an exception, even though underlying sockets have already been cleaned up; close() on an SSLSocketImpl requires a shutdown handshake in order to shut down cleanly, and if the connection has been broken already, then this is not possible, and the SSLSocketImpl was already responsible for performing local cleanup at the time the exception was raised.
-
close
public void close()
Closes this channel.
-
position
public long position() throws IOExceptionReturns this channel's current position.- Specified by:
positionin interfaceSeekableByteChannel- Returns:
- this channel's current position
- Throws:
IOException
-
position
@CanIgnoreReturnValue public SeekableByteChannel position(long newPosition) throws IOException
Sets this channel's position.This method will throw an exception if
newPositionis greater than object size, which contradictsSeekableByteChannelcontract. TODO(user): decide if this needs to be fixed.- Specified by:
positionin interfaceSeekableByteChannel- Parameters:
newPosition- the new position, counting the number of bytes from the beginning.- Returns:
- this channel instance
- Throws:
FileNotFoundException- if the underlying object does not exist.IOException- on IO error
-
size
public long size() throws IOExceptionReturns size of the object to which this channel is connected.Note: this method will return -1 until metadata will be lazily initialized during first
read(java.nio.ByteBuffer)method call.- Specified by:
sizein interfaceSeekableByteChannel- Returns:
- size of the object to which this channel is connected after metadata was initialized
(during first read) or
-1otherwise. - Throws:
IOException- on IO error
-
setSize
protected void setSize(long size)
Sets size of this channel to the given value.
-
validatePosition
protected void validatePosition(long position) throws IOExceptionValidates that the given position is valid for this channel.- Throws:
IOException
-
initMetadata
protected void initMetadata(com.google.api.client.http.HttpHeaders headers) throws IOExceptionInitializes metadata (size, encoding, etc) from HTTPheaders. Used for lazy initialization when fail fast is disabled.- Throws:
IOException
-
initMetadata
protected void initMetadata(@Nullable String encoding, long sizeFromMetadata, long generation) throws IOExceptionInitializes metadata (size, encoding, etc) from passed parameters.- Throws:
IOException
-
openStream
protected InputStream openStream(long bytesToRead) throws IOException
Opens the underlying stream, sets its position to thecurrentPosition.If the file encoding in GCS is gzip (and therefore the HTTP client will decompress it), the entire file is always requested, and we seek to the position requested. If the file encoding is not gzip, only the remaining bytes to be read are requested from GCS.
- Parameters:
bytesToRead- number of bytes to read from new stream. Ignored ifGoogleCloudStorageReadOptions.getFadvise()is equal toGoogleCloudStorageReadOptions.Fadvise.SEQUENTIAL.- Throws:
IOException- on IO error
-
createDataRequest
protected com.google.api.services.storage.Storage.Objects.Get createDataRequest() throws IOException- Throws:
IOException
-
createMetadataRequest
protected com.google.api.services.storage.Storage.Objects.Get createMetadataRequest() throws IOException- Throws:
IOException
-
-