public URI addToURI(final URI uri) throws URISyntaxException, StorageException {
        final String origRawQuery = uri.getRawQuery();
        final String rawFragment = uri.getRawFragment();
        final String uriString = uri.resolve(uri).toASCIIString();

        final HashMap<String, String[]> origQueryMap = PathUtility.parseQueryString(origRawQuery);

        // Try/Insert original queries to map

        for (final Entry<String, String[]> entry : origQueryMap.entrySet()) {
            for (final String val : entry.getValue()) {
                this.insertKeyValue(entry.getKey(), val);
            }
        }

        final StringBuilder retBuilder = new StringBuilder();

        // has a fragment
        if (Utility.isNullOrEmpty(origRawQuery) && !Utility.isNullOrEmpty(rawFragment)) {
            final int bangDex = uriString.indexOf('#');
            retBuilder.append(uriString.substring(0, bangDex));
        }
        else if (!Utility.isNullOrEmpty(origRawQuery)) {
            // has a query
            final int queryDex = uriString.indexOf('?');
            retBuilder.append(uriString.substring(0, queryDex));
        }
        else {
            // no fragment or query
            retBuilder.append(uriString);
            if (uri.getRawPath().length() <= 0) {
                retBuilder.append("/");
            }
        }

        final String finalQuery = this.toString();

        if (finalQuery.length() > 0) {
            retBuilder.append("?");
            retBuilder.append(finalQuery);
        }

        if (!Utility.isNullOrEmpty(rawFragment)) {
            retBuilder.append("#");
            retBuilder.append(rawFragment);
        }

        return new URI(retBuilder.toString());
    }

public
URI
addToURI
(
final
URI
uri
)
throws
URISyntaxException
,
StorageException
{
final
String
origRawQuery
=
uri
.
getRawQuery
(
)
;
final
String
rawFragment
=
uri
.
getRawFragment
(
)
;
final
String
uriString
=
uri
.
resolve
(
uri
)
.
toASCIIString
(
)
;
final
HashMap
<
String
,
String
[
]
>
origQueryMap
=
PathUtility
.
parseQueryString
(
origRawQuery
)
;
// Try/Insert original queries to map
for
(
final
Entry
<
String
,
String
[
]
>
entry
:
origQueryMap
.
entrySet
(
)
)
{
for
(
final
String
val
:
entry
.
getValue
(
)
)
{
this
.
insertKeyValue
(
entry
.
getKey
(
)
,
val
)
;
}
}
final
StringBuilder
retBuilder
=
new
StringBuilder
(
)
;
// has a fragment
if
(
Utility
.
isNullOrEmpty
(
origRawQuery
)
&&
!
Utility
.
isNullOrEmpty
(
rawFragment
)
)
{
final
int
bangDex
=
uriString
.
indexOf
(
'
'
)
;
retBuilder
.
append
(
uriString
.
substring
(
0
,
bangDex
)
)
;
}
else
if
(
!
Utility
.
isNullOrEmpty
(
origRawQuery
)
)
{
// has a query
final
int
queryDex
=
uriString
.
indexOf
(
'
'
)
;
retBuilder
.
append
(
uriString
.
substring
(
0
,
queryDex
)
)
;
}
else
{
// no fragment or query
retBuilder
.
append
(
uriString
)
;
if
(
uri
.
getRawPath
(
)
.
length
(
)
<=
0
)
{
retBuilder
.
append
(
"/"
)
;
}
}
final
String
finalQuery
=
this
.
toString
(
)
;
if
(
finalQuery
.
length
(
)
>
0
)
{
retBuilder
.
append
(
"?"
)
;
retBuilder
.
append
(
finalQuery
)
;
}
if
(
!
Utility
.
isNullOrEmpty
(
rawFragment
)
)
{
retBuilder
.
append
(
"#"
)
;
retBuilder
.
append
(
rawFragment
)
;
}
return
new
URI
(
retBuilder
.
toString
(
)
)
;
}

Add query parameter to an existing Uri. This takes care of any existing query parameters in the Uri.

@param uri
the original uri.
@return the appended uri
@throws URISyntaxException
if the resulting uri is invalid.
@throws StorageException

Add query parameter to an existing Uri . This takes care of any existing query parameters in the Uri .


public static void addOptionalHeader(final HttpURLConnection request, final String name, final String value) {
        if (value != null && !value.equals(Constants.EMPTY_STRING)) {
            request.setRequestProperty(name, value);
        }
    }

public static void addOptionalHeader ( final HttpURLConnection request , final String name , final String value ) { if ( value != null && ! value . equals ( Constants . EMPTY_STRING ) ) { request . setRequestProperty ( name , value ) ; } }

Adds the optional header.

@param request
a HttpURLConnection for the operation.
@param name
the metadata name.
@param value
the metadata value.


public static HttpURLConnection createURLConnection(final URI uri, final RequestOptions options,
            UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException,
            StorageException {
        if (builder == null) {
            builder = new UriQueryBuilder();
        }

        if (options.getTimeoutIntervalInMs() != null && options.getTimeoutIntervalInMs() != 0) {
            builder.add(TIMEOUT, String.valueOf(options.getTimeoutIntervalInMs() / 1000));
        }

        final URL resourceUrl = builder.addToURI(uri).toURL();

        // Get the proxy settings
        Proxy proxy = OperationContext.getDefaultProxy();
        if (opContext != null && opContext.getProxy() != null) {
            proxy = opContext.getProxy();
        }

        // Set up connection, optionally with proxy settings
        final HttpURLConnection retConnection;
        if (proxy != null) {
            retConnection = (HttpURLConnection) resourceUrl.openConnection(proxy);
        }
        else {
            retConnection = (HttpURLConnection) resourceUrl.openConnection();
        }

        /*
         * ReadTimeout must be explicitly set to avoid a bug in JDK 6. In certain cases, this bug causes an immediate
         * read timeout exception to be thrown even if ReadTimeout is not set.
         *
         * Both connect and read timeout are set to the same value as we have no way of knowing how to partition
         * the remaining time between these operations. The user can override these timeouts using the SendingRequest
         * event handler if more control is desired.
         */
        int timeout = Utility.getRemainingTimeout(options.getOperationExpiryTimeInMs(), options.getTimeoutIntervalInMs());
        retConnection.setReadTimeout(timeout);
        retConnection.setConnectTimeout(timeout);

        // Note : by default sends Accept behavior as text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
        retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT, Constants.HeaderConstants.XML_TYPE);
        retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_CHARSET, Constants.UTF8_CHARSET);

        // Note: by default sends Accept-Encoding as gzip
        retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_ENCODING, Constants.EMPTY_STRING);

        // Note : by default sends Content-type behavior as application/x-www-form-urlencoded for posts.
        retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, Constants.EMPTY_STRING);

        retConnection.setRequestProperty(Constants.HeaderConstants.STORAGE_VERSION_HEADER,
                Constants.HeaderConstants.TARGET_STORAGE_VERSION);
        retConnection.setRequestProperty(Constants.HeaderConstants.USER_AGENT, getUserAgent());
        retConnection.setRequestProperty(Constants.HeaderConstants.CLIENT_REQUEST_ID_HEADER,
                opContext.getClientRequestID());

        return retConnection;
    }

Creates the web request.

@param uri
the request Uri.
@param options
A {@link RequestOptions} object that specifies execution options such as retry policy and timeout
settings for the operation. This parameter is unused.
@param builder
the UriQueryBuilder for the request
@param opContext
an object used to track the execution of the operation
@return a HttpURLConnection to perform the operation.
@throws IOException
if there is an error opening the connection
@throws URISyntaxException
if there is an improperly formated URI
@throws StorageException


public static HttpURLConnection delete(final URI uri, final RequestOptions options, UriQueryBuilder builder,
            final OperationContext opContext) throws IOException, URISyntaxException, StorageException {
        if (builder == null) {
            builder = new UriQueryBuilder();
        }

        final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
        retConnection.setRequestMethod(Constants.HTTP_DELETE);

        return retConnection;
    }

public static HttpURLConnection delete ( final URI uri , final RequestOptions options , UriQueryBuilder builder , final OperationContext opContext ) throws IOException , URISyntaxException , StorageException { if ( builder == null ) { builder = new UriQueryBuilder ( ) ; } final HttpURLConnection retConnection = createURLConnection ( uri , options , builder , opContext ) ; retConnection . setRequestMethod ( Constants . HTTP_DELETE ) ; return retConnection ; }

Deletes the specified resource. Sign with no length specified.

@param uri
the request Uri.
@param timeout
the timeout for the request
@param builder
the UriQueryBuilder for the request
@param opContext
an object used to track the execution of the operation
@return a HttpURLConnection to perform the operation.
@throws IOException
if there is an error opening the connection
@throws URISyntaxException
if there is an improperly formated URI
@throws StorageException

Deletes the specified resource . Sign with no length specified .


public static HttpURLConnection getServiceProperties(final URI uri, final RequestOptions options,
            UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException,
            StorageException {
        if (builder == null) {
            builder = new UriQueryBuilder();
        }

        builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES);
        builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE);

        final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
        retConnection.setRequestMethod(Constants.HTTP_GET);

        return retConnection;
    }

public static HttpURLConnection getServiceProperties ( final URI uri , final RequestOptions options , UriQueryBuilder builder , final OperationContext opContext ) throws IOException , URISyntaxException , StorageException { if ( builder == null ) { builder = new UriQueryBuilder ( ) ; } builder . add ( Constants . QueryConstants . COMPONENT , Constants . QueryConstants . PROPERTIES ) ; builder . add ( Constants . QueryConstants . RESOURCETYPE , SERVICE ) ; final HttpURLConnection retConnection = createURLConnection ( uri , options , builder , opContext ) ; retConnection . setRequestMethod ( Constants . HTTP_GET ) ; return retConnection ; }

Creates a HttpURLConnection used to retrieve the Analytics service properties from the storage service.

@param uri
The service endpoint.
@param timeout
The timeout.
@param builder
The builder.
@param opContext
an object used to track the execution of the operation
@return a web request for performing the operation.
@throws IOException
@throws URISyntaxException
@throws StorageException

Creates a HttpURLConnection used to retrieve the Analytics service properties from the storage service .


public static String getUserAgent() {
        if (userAgent == null) {
            String userAgentComment = String.format(Utility.LOCALE_US, "(Android %s; %s; %s)",
                    android.os.Build.VERSION.RELEASE, android.os.Build.BRAND, android.os.Build.MODEL);
            userAgent = String.format("%s/%s %s", Constants.HeaderConstants.USER_AGENT_PREFIX,
                    Constants.HeaderConstants.USER_AGENT_VERSION, userAgentComment);
        }

        return userAgent;
    }

public
static
String
getUserAgent
(
)
{
if
(
userAgent
==
)
{
String
userAgentComment
=
String
.
format
(
Utility
.
LOCALE_US
,
"(Android %s; %s; %s)"
,
android
.
os
.
Build
.
VERSION
.
RELEASE
,
android
.
os
.
Build
.
BRAND
,
android
.
os
.
Build
.
MODEL
)
;
userAgent
=
String
.
format
(
"%s/%s %s"
,
Constants
.
HeaderConstants
.
USER_AGENT_PREFIX
,
Constants
.
HeaderConstants
.
USER_AGENT_VERSION
,
userAgentComment
)
;
}
return
userAgent
;
}

Gets the user agent to send over the wire to identify the client.

@return the user agent to send over the wire to identify the client.

Gets the user agent to send over the wire to identify the client .


public static HttpURLConnection setMetadata(final URI uri, final RequestOptions options, UriQueryBuilder builder,
            final OperationContext opContext) throws IOException, URISyntaxException, StorageException {

        if (builder == null) {
            builder = new UriQueryBuilder();
        }

        builder.add(Constants.QueryConstants.COMPONENT, METADATA);
        final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);

        retConnection.setFixedLengthStreamingMode(0);
        retConnection.setDoOutput(true);
        retConnection.setRequestMethod(Constants.HTTP_PUT);

        return retConnection;
    }

public static HttpURLConnection setMetadata ( final URI uri , final RequestOptions options , UriQueryBuilder builder , final OperationContext opContext ) throws IOException , URISyntaxException , StorageException { if ( builder == null ) { builder = new UriQueryBuilder ( ) ; } builder . add ( Constants . QueryConstants . COMPONENT , METADATA ) ; final HttpURLConnection retConnection = createURLConnection ( uri , options , builder , opContext ) ; retConnection . setFixedLengthStreamingMode ( 0 ) ; retConnection . setDoOutput ( true ) ; retConnection . setRequestMethod ( Constants . HTTP_PUT ) ; return retConnection ; }

Sets the metadata. Sign with 0 length.

@param uri
The blob Uri.
@param timeout
The timeout.
@param builder
The builder.
@param opContext
an object used to track the execution of the operation
@return a web request for performing the operation.
@throws StorageException
@throws URISyntaxException
@throws IOException

Sets the metadata . Sign with 0 length .


public static HttpURLConnection setServiceProperties(final URI uri, final RequestOptions options,
            UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException,
            StorageException {
        if (builder == null) {
            builder = new UriQueryBuilder();
        }

        builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES);
        builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE);

        final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);

        retConnection.setDoOutput(true);
        retConnection.setRequestMethod(Constants.HTTP_PUT);

        return retConnection;
    }

public static HttpURLConnection setServiceProperties ( final URI uri , final RequestOptions options , UriQueryBuilder builder , final OperationContext opContext ) throws IOException , URISyntaxException , StorageException { if ( builder == null ) { builder = new UriQueryBuilder ( ) ; } builder . add ( Constants . QueryConstants . COMPONENT , Constants . QueryConstants . PROPERTIES ) ; builder . add ( Constants . QueryConstants . RESOURCETYPE , SERVICE ) ; final HttpURLConnection retConnection = createURLConnection ( uri , options , builder , opContext ) ; retConnection . setDoOutput ( true ) ; retConnection . setRequestMethod ( Constants . HTTP_PUT ) ; return retConnection ; }

Creates a HttpURLConnection used to set the Analytics service properties on the storage service.

@param uri
The service endpoint.
@param timeout
The timeout.
@param builder
The builder.
@param opContext
an object used to track the execution of the operation
@return a web request for performing the operation.
@throws IOException
@throws URISyntaxException
@throws StorageException

Creates a HttpURLConnection used to set the Analytics service properties on the storage service .


@Override
    @DoesServiceRequest
    public void close() throws IOException {
        try {
            // if the user has already closed the stream, this will throw a STREAM_CLOSED exception
            // if an exception was thrown by any thread in the threadExecutor, realize it now
            this.checkStreamState();

            // flush any remaining data
            this.flush();

            // shut down the ExecutorService.
            this.threadExecutor.shutdown();

            // try to commit the file
            try {
                this.commit();
            }
            catch (final StorageException e) {
                throw Utility.initIOException(e);
            } catch (URISyntaxException e) {
                throw Utility.initIOException(e);
            }
        }
        finally {
            // if close() is called again, an exception will be thrown
            synchronized (this.lastErrorLock) {
                this.streamFaulted = true;
                this.lastError = new IOException(SR.STREAM_CLOSED);
            }

            // if an exception was thrown and the executor was not yet closed, call shutDownNow() to cancel all tasks
            // and shutdown the ExecutorService
            if (!this.threadExecutor.isShutdown()) {
                this.threadExecutor.shutdownNow();
            }
        }
    }

Closes this output stream and releases any system resources associated with this stream. If any data remains in
the buffer it is committed to the service.

@throws IOException
If an I/O error occurs.

Closes this output stream and releases any system resources associated with this stream . If any data remains in the buffer it is committed to the service .


@DoesServiceRequest
    private void commit() throws StorageException, URISyntaxException {
        if (this.options.getStoreFileContentMD5()) {
            this.parentFileRef.getProperties().setContentMD5(Base64.encode(this.md5Digest.digest()));
        }

        this.parentFileRef.uploadProperties(this.accessCondition, this.options, this.opContext);
    }

@ DoesServiceRequest private void commit ( ) throws StorageException , URISyntaxException { if ( this . options . getStoreFileContentMD5 ( ) ) { this . parentFileRef . getProperties ( ) . setContentMD5 ( Base64 . encode ( this . md5Digest . digest ( ) ) ) ; } this . parentFileRef . uploadProperties ( this . accessCondition , this . options , this . opContext ) ; }

Commits the file.

@throws StorageException
An exception representing any error which occurred during the operation.
@throws URISyntaxException


@DoesServiceRequest
    private synchronized void dispatchWrite(final int writeLength) throws IOException {
        if (writeLength == 0) {
            return;
        }

        Callable<Void> worker = null;

        if (this.outstandingRequests > this.options.getConcurrentRequestCount() * 2) {
            this.waitForTaskToComplete();
        }

        final ByteArrayInputStream bufferRef = new ByteArrayInputStream(this.outBuffer.toByteArray());
        final CloudFile fileRef = this.parentFileRef;
        long tempOffset = this.currentOffset;
        long tempLength = writeLength;

        final long opWriteLength = tempLength;
        final long opOffset = tempOffset;
        this.currentOffset += writeLength;

        worker = new Callable<Void>() {
            @Override
            public Void call() {
                try {
                    fileRef.uploadRange(bufferRef, opOffset, opWriteLength, FileOutputStream.this.accessCondition,
                            FileOutputStream.this.options, FileOutputStream.this.opContext);
                }
                catch (final IOException e) {
                    synchronized (FileOutputStream.this.lastErrorLock) {
                        FileOutputStream.this.streamFaulted = true;
                        FileOutputStream.this.lastError = e;
                    }
                }
                catch (final StorageException e) {
                    synchronized (FileOutputStream.this.lastErrorLock) {
                        FileOutputStream.this.streamFaulted = true;
                        FileOutputStream.this.lastError = Utility.initIOException(e);
                    }
                } catch (URISyntaxException e) {
                    synchronized (FileOutputStream.this.lastErrorLock) {
                        FileOutputStream.this.streamFaulted = true;
                        FileOutputStream.this.lastError = Utility.initIOException(e);
                    }
                }

                return null;
            }
        };

        // Do work and reset buffer.
        this.completionService.submit(worker);
        this.outstandingRequests++;
        this.currentBufferedBytes = 0;
        this.outBuffer = new ByteArrayOutputStream();
    }

@
DoesServiceRequest
private
synchronized
void
dispatchWrite
(
final
int
writeLength
)
throws
IOException
{
if
(
writeLength
==
0
)
{
return
;
}
Callable
<
Void
>
worker
=
;
if
(
this
.
outstandingRequests
>
this
.
options
.
getConcurrentRequestCount
(
)
*
2
)
{
this
.
waitForTaskToComplete
(
)
;
}
final
ByteArrayInputStream
bufferRef
=
new
ByteArrayInputStream
(
this
.
outBuffer
.
toByteArray
(
)
)
;
final
CloudFile
fileRef
=
this
.
parentFileRef
;
long
tempOffset
=
this
.
currentOffset
;
long
tempLength
=
writeLength
;
final
long
opWriteLength
=
tempLength
;
final
long
opOffset
=
tempOffset
;
this
.
currentOffset
+=
writeLength
;
worker
=
new
Callable
<
Void
>
(
)
{
@
Override
public
Void
call
(
)
{
try
{
fileRef
.
uploadRange
(
bufferRef
,
opOffset
,
opWriteLength
,
FileOutputStream
.
this
.
accessCondition
,
FileOutputStream
.
this
.
options
,
FileOutputStream
.
this
.
opContext
)
;
}
catch
(
final
IOException
e
)
{
synchronized
(
FileOutputStream
.
this
.
lastErrorLock
)
{
FileOutputStream
.
this
.
streamFaulted
=
true
;
FileOutputStream
.
this
.
lastError
=
e
;
}
}
catch
(
final
StorageException
e
)
{
synchronized
(
FileOutputStream
.
this
.
lastErrorLock
)
{
FileOutputStream
.
this
.
streamFaulted
=
true
;
FileOutputStream
.
this
.
lastError
=
Utility
.
initIOException
(
e
)
;
}
}
catch
(
URISyntaxException
e
)
{
synchronized
(
FileOutputStream
.
this
.
lastErrorLock
)
{
FileOutputStream
.
this
.
streamFaulted
=
true
;
FileOutputStream
.
this
.
lastError
=
Utility
.
initIOException
(
e
)
;
}
}
return
;
}
}
;
// Do work and reset buffer.
this
.
completionService
.
submit
(
worker
)
;
this
.
outstandingRequests
++
;
this
.
currentBufferedBytes
=
0
;
this
.
outBuffer
=
new
ByteArrayOutputStream
(
)
;
}

Dispatches a write operation for a given length.

@param writeLength
An int which represents the length of the data to write, this is the write threshold that
triggered the write.

@throws IOException
If an I/O error occurs. In particular, an IOException may be thrown if the output stream has been
closed.

Dispatches a write operation for a given length .


@Override
    @DoesServiceRequest
    public synchronized void flush() throws IOException {
        this.checkStreamState();

        // Dispatch a write for the current bytes in the buffer
        this.dispatchWrite(this.currentBufferedBytes);

        // Waits for all submitted tasks to complete
        while (this.outstandingRequests > 0) {
            // Wait for a task to complete
            this.waitForTaskToComplete();

            // If that task threw an error, fail fast
            this.checkStreamState();
        }
    }

Flushes this output stream and forces any buffered output bytes to be written out. If any data remains in the
buffer it is committed to the service.

@throws IOException
If an I/O error occurs.

Flushes this output stream and forces any buffered output bytes to be written out . If any data remains in the buffer it is committed to the service .


private void waitForTaskToComplete() throws IOException {
        try {
            final Future<Void> future = this.completionService.take();
            future.get();
        }
        catch (final InterruptedException e) {
            throw Utility.initIOException(e);
        }
        catch (final ExecutionException e) {
            throw Utility.initIOException(e);
        }

        this.outstandingRequests--;
    }

private void waitForTaskToComplete ( ) throws IOException { try { final Future < Void > future = this . completionService . take ( ) ; future . get ( ) ; } catch ( final InterruptedException e ) { throw Utility . initIOException ( e ) ; } catch ( final ExecutionException e ) { throw Utility . initIOException ( e ) ; } this . outstandingRequests -- ; }

Waits for one task to complete

@throws IOException
If an I/O error occurs. In particular, an IOException may be thrown if the output stream has been
closed.


@Override
    @DoesServiceRequest
    public void write(final byte[] data, final int offset, final int length) throws IOException {
        if (offset < 0 || length < 0 || length > data.length - offset) {
            throw new IndexOutOfBoundsException();
        }

        this.writeInternal(data, offset, length);
    }

@ Override @ DoesServiceRequest public void write ( final byte [ ] data , final int offset , final int length ) throws IOException { if ( offset < 0 || length < 0 || length > data . length - offset ) { throw new IndexOutOfBoundsException ( ) ; } this . writeInternal ( data , offset , length ) ; }

Writes length bytes from the specified byte array starting at offset to this output stream.

@param data
A byte array which represents the data to write.
@param offset
An int which represents the start offset in the data.
@param length
An int which represents the number of bytes to write.

@throws IOException
If an I/O error occurs. In particular, an IOException may be thrown if the output stream has been
closed.

Writes length bytes from the specified byte array starting at offset to this output stream .


@DoesServiceRequest
    public void write(final InputStream sourceStream, final long writeLength) throws IOException, StorageException {
        Utility.writeToOutputStream(sourceStream, this, writeLength, false, false, this.opContext, this.options, false);
    }

@ DoesServiceRequest public void write ( final InputStream sourceStream , final long writeLength ) throws IOException , StorageException { Utility . writeToOutputStream ( sourceStream , this , writeLength , false , false , this . opContext , this . options , false ) ; }

Writes all data from the InputStream to the File.

@param sourceStream
An {@link InputStream} object which species the data to write to the File.

@throws IOException
If an I/O error occurs. In particular, an IOException may be thrown if the output stream has been
closed.
@throws StorageException
An exception representing any error which occurred during the operation.

Writes all data from the InputStream to the File .


@DoesServiceRequest
    private synchronized void writeInternal(final byte[] data, int offset, int length) throws IOException {
        while (length > 0) {
            this.checkStreamState();

            final int availableBufferBytes = this.internalWriteThreshold - this.currentBufferedBytes;
            final int nextWrite = Math.min(availableBufferBytes, length);

            // If we need to set MD5 then update the digest accordingly
            if (this.options.getStoreFileContentMD5()) {
                this.md5Digest.update(data, offset, nextWrite);
            }

            this.outBuffer.write(data, offset, nextWrite);
            this.currentBufferedBytes += nextWrite;
            offset += nextWrite;
            length -= nextWrite;

            if (this.currentBufferedBytes == this.internalWriteThreshold) {
                this.dispatchWrite(this.internalWriteThreshold);
            }
        }
    }

Writes the data to the buffer and triggers writes to the service as needed.

@param data
A byte array which represents the data to write.
@param offset
An int which represents the start offset in the data.
@param length
An int which represents the number of bytes to write.

@throws IOException
If an I/O error occurs. In particular, an IOException may be thrown if the output stream has been
closed.

Writes the data to the buffer and triggers writes to the service as needed .


private static String getDNS(String service, String base) {
        if (base == null) {
            base = DEFAULT_DNS;
        }

        return String.format(DNS_NAME_FORMAT, service, base);
    }

private static String getDNS ( String service , String base ) { if ( base == null ) { base = DEFAULT_DNS ; } return String . format ( DNS_NAME_FORMAT , service , base ) ; }

This generates a domain name for the given service.

@param service
the service to connect to
@param base
the suffix to use
@return the domain name

This generates a domain name for the given service .


private static CloudStorageAccount tryConfigureDevStore(final Map<String, String> settings)
            throws URISyntaxException {
        if (matchesSpecification(
                settings,
                allRequired(USE_DEVELOPMENT_STORAGE_NAME),
                optional(DEVELOPMENT_STORAGE_PROXY_URI_NAME))) {
            if (!Boolean.parseBoolean(settings.get(USE_DEVELOPMENT_STORAGE_NAME))) {
                throw new IllegalArgumentException(SR.INVALID_CONNECTION_STRING_DEV_STORE_NOT_TRUE);
            }

            URI devStoreProxyUri = null;

            if (settings.containsKey(DEVELOPMENT_STORAGE_PROXY_URI_NAME)) {
                devStoreProxyUri = new URI(settings.get(DEVELOPMENT_STORAGE_PROXY_URI_NAME));
            }

            return getDevelopmentStorageAccount(devStoreProxyUri);
        } else {
            return null;
        }
    }

Evaluates connection settings and returns a CloudStorageAccount representing Development Storage.

@param settings
A java.util.Map of key/value pairs which represents the connection settings.
@return A {@link CloudStorageAccount} object constructed from the values provided in the connection settings, or
null if
one cannot be constructed.
@throws URISyntaxException
if the connection settings contains an invalid URI

Evaluates connection settings and returns a CloudStorageAccount representing Development Storage .


private static CloudStorageAccount tryConfigureServiceAccount(final Map<String, String> settings)
            throws URISyntaxException, InvalidKeyException {

        ConnectionStringFilter endpointsOptional =
                optional(
                        BLOB_ENDPOINT_NAME, BLOB_SECONDARY_ENDPOINT_NAME,
                        QUEUE_ENDPOINT_NAME, QUEUE_SECONDARY_ENDPOINT_NAME,
                        TABLE_ENDPOINT_NAME, TABLE_SECONDARY_ENDPOINT_NAME,
                        FILE_ENDPOINT_NAME, FILE_SECONDARY_ENDPOINT_NAME
                );

        ConnectionStringFilter primaryEndpointRequired =
                atLeastOne(
                        BLOB_ENDPOINT_NAME,
                        QUEUE_ENDPOINT_NAME,
                        TABLE_ENDPOINT_NAME,
                        FILE_ENDPOINT_NAME
                );

        ConnectionStringFilter secondaryEndpointsOptional =
                optional(
                        BLOB_SECONDARY_ENDPOINT_NAME,
                        QUEUE_SECONDARY_ENDPOINT_NAME,
                        TABLE_SECONDARY_ENDPOINT_NAME,
                        FILE_SECONDARY_ENDPOINT_NAME
                );

        ConnectionStringFilter automaticEndpointsMatchSpec =
                matchesExactly(matchesAll(
                        matchesOne(
                                matchesAll(allRequired(ACCOUNT_KEY_NAME)), // Key + Name, Endpoints optional
                                allRequired(SHARED_ACCESS_SIGNATURE_NAME) // SAS + Name, Endpoints optional
                        ),
                        allRequired(ACCOUNT_NAME_NAME), // Name required to automatically create URIs
                        endpointsOptional,
                        optional(DEFAULT_ENDPOINTS_PROTOCOL_NAME, ENDPOINT_SUFFIX_NAME)
                ));

        ConnectionStringFilter explicitEndpointsMatchSpec =
                matchesExactly(matchesAll( // Any Credentials, Endpoints must be explicitly declared
                        validCredentials,
                        primaryEndpointRequired,
                        secondaryEndpointsOptional
                ));

        Boolean matchesAutomaticEndpointsSpec = matchesSpecification(settings, automaticEndpointsMatchSpec);
        Boolean matchesExplicitEndpointsSpec = matchesSpecification(settings, explicitEndpointsMatchSpec);

        if (matchesAutomaticEndpointsSpec || matchesExplicitEndpointsSpec) {
            if (matchesAutomaticEndpointsSpec && !settings.containsKey(DEFAULT_ENDPOINTS_PROTOCOL_NAME)) {
                settings.put(DEFAULT_ENDPOINTS_PROTOCOL_NAME, "https");
            }

            String blobEndpoint = settingOrDefault(settings, BLOB_ENDPOINT_NAME);
            String queueEndpoint = settingOrDefault(settings, QUEUE_ENDPOINT_NAME);
            String tableEndpoint = settingOrDefault(settings, TABLE_ENDPOINT_NAME);
            String fileEndpoint = settingOrDefault(settings, FILE_ENDPOINT_NAME);
            String blobSecondaryEndpoint = settingOrDefault(settings, BLOB_SECONDARY_ENDPOINT_NAME);
            String queueSecondaryEndpoint = settingOrDefault(settings, QUEUE_SECONDARY_ENDPOINT_NAME);
            String tableSecondaryEndpoint = settingOrDefault(settings, TABLE_SECONDARY_ENDPOINT_NAME);
            String fileSecondaryEndpoint = settingOrDefault(settings, FILE_SECONDARY_ENDPOINT_NAME);

            // if secondary is specified, primary must also be specified

            if (
                    isValidEndpointPair(blobEndpoint, blobSecondaryEndpoint)
                            && isValidEndpointPair(queueEndpoint, queueSecondaryEndpoint)
                            && isValidEndpointPair(tableEndpoint, tableSecondaryEndpoint)
                            && isValidEndpointPair(fileEndpoint, fileSecondaryEndpoint)
                    ) {
                CloudStorageAccount accountInformation =
                        new CloudStorageAccount(
                                StorageCredentials.tryParseCredentials(settings),
                                getStorageUri(settings, SR.BLOB, BLOB_ENDPOINT_NAME, BLOB_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec),
                                getStorageUri(settings, SR.QUEUE, QUEUE_ENDPOINT_NAME, QUEUE_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec),
                                getStorageUri(settings, SR.TABLE, TABLE_ENDPOINT_NAME, TABLE_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec),
                                getStorageUri(settings, SR.FILE, FILE_ENDPOINT_NAME, FILE_SECONDARY_ENDPOINT_NAME, matchesAutomaticEndpointsSpec)
                        );

                accountInformation.isBlobEndpointDefault = blobEndpoint == null;
                accountInformation.isFileEndpointDefault = fileEndpoint == null;
                accountInformation.isQueueEndpointDefault = queueEndpoint == null;
                accountInformation.isTableEndpointDefault = tableEndpoint == null;

                accountInformation.endpointSuffix = settingOrDefault(settings, ENDPOINT_SUFFIX_NAME);

                accountInformation.accountName = settingOrDefault(settings, ACCOUNT_NAME_NAME);

                return accountInformation;
            }
        }

        return null;
    }

Evaluates connection settings and configures a CloudStorageAccount accordingly.

@param settings
A java.util.Map of key/value pairs which represents
the connection settings.
@return A {@link CloudStorageAccount} represented by the settings.
@throws URISyntaxException
if the connectionString specifies an invalid URI.
@throws InvalidKeyException
if credentials in the connection settings contain an invalid key.

Evaluates connection settings and configures a CloudStorageAccount accordingly .


public CloudAnalyticsClient createCloudAnalyticsClient() {
        if (this.getBlobStorageUri() == null) {
            throw new IllegalArgumentException(SR.BLOB_ENDPOINT_NOT_CONFIGURED);
        }

        if (this.getTableStorageUri() == null) {
            throw new IllegalArgumentException(SR.TABLE_ENDPOINT_NOT_CONFIGURED);
        }

        if (this.credentials == null) {
            throw new IllegalArgumentException(SR.MISSING_CREDENTIALS);
        }

        return new CloudAnalyticsClient(this.getBlobStorageUri(), this.getTableStorageUri(), this.getCredentials());
    }

public CloudAnalyticsClient createCloudAnalyticsClient ( ) { if ( this . getBlobStorageUri ( ) == null ) { throw new IllegalArgumentException ( SR . BLOB_ENDPOINT_NOT_CONFIGURED ) ; } if ( this . getTableStorageUri ( ) == null ) { throw new IllegalArgumentException ( SR . TABLE_ENDPOINT_NOT_CONFIGURED ) ; } if ( this . credentials == null ) { throw new IllegalArgumentException ( SR . MISSING_CREDENTIALS ) ; } return new CloudAnalyticsClient ( this . getBlobStorageUri ( ) , this . getTableStorageUri ( ) , this . getCredentials ( ) ) ; }

Creates a new Analytics service client.

@return An analytics client object that uses the Blob and Table service endpoints.

Creates a new Analytics service client .


public CloudBlobClient createCloudBlobClient() {
        if (this.getBlobStorageUri() == null) {
            throw new IllegalArgumentException(SR.BLOB_ENDPOINT_NOT_CONFIGURED);
        }

        if (this.credentials == null) {
            throw new IllegalArgumentException(SR.MISSING_CREDENTIALS);
        }

        return new CloudBlobClient(this.getBlobStorageUri(), this.getCredentials());
    }

public CloudBlobClient createCloudBlobClient ( ) { if ( this . getBlobStorageUri ( ) == null ) { throw new IllegalArgumentException ( SR . BLOB_ENDPOINT_NOT_CONFIGURED ) ; } if ( this . credentials == null ) { throw new IllegalArgumentException ( SR . MISSING_CREDENTIALS ) ; } return new CloudBlobClient ( this . getBlobStorageUri ( ) , this . getCredentials ( ) ) ; }

Creates a new Blob service client.

@return A {@link CloudBlobClient} that represents the cloud Blob client.


public CloudFileClient createCloudFileClient() {
        if (this.getFileStorageUri() == null) {
            throw new IllegalArgumentException(SR.FILE_ENDPOINT_NOT_CONFIGURED);
        }

        if (this.credentials == null) {
            throw new IllegalArgumentException(SR.MISSING_CREDENTIALS);
        }

        if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) {

            throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST);
        }

        return new CloudFileClient(this.getFileStorageUri(), this.getCredentials());
    }

public CloudFileClient createCloudFileClient ( ) { if ( this . getFileStorageUri ( ) == null ) { throw new IllegalArgumentException ( SR . FILE_ENDPOINT_NOT_CONFIGURED ) ; } if ( this . credentials == null ) { throw new IllegalArgumentException ( SR . MISSING_CREDENTIALS ) ; } if ( ! StorageCredentialsHelper . canCredentialsGenerateClient ( this . credentials ) ) { throw new IllegalArgumentException ( SR . CREDENTIALS_CANNOT_SIGN_REQUEST ) ; } return new CloudFileClient ( this . getFileStorageUri ( ) , this . getCredentials ( ) ) ; }

Creates a new File service client.

@return A {@link CloudFileClient} that represents the cloud File client.


public CloudQueueClient createCloudQueueClient() {
        if (this.getQueueStorageUri() == null) {
            throw new IllegalArgumentException(SR.QUEUE_ENDPOINT_NOT_CONFIGURED);
        }

        if (this.credentials == null) {
            throw new IllegalArgumentException(SR.MISSING_CREDENTIALS);
        }

        if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) {

            throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST);
        }

        return new CloudQueueClient(this.getQueueStorageUri(), this.getCredentials());
    }

public CloudQueueClient createCloudQueueClient ( ) { if ( this . getQueueStorageUri ( ) == null ) { throw new IllegalArgumentException ( SR . QUEUE_ENDPOINT_NOT_CONFIGURED ) ; } if ( this . credentials == null ) { throw new IllegalArgumentException ( SR . MISSING_CREDENTIALS ) ; } if ( ! StorageCredentialsHelper . canCredentialsGenerateClient ( this . credentials ) ) { throw new IllegalArgumentException ( SR . CREDENTIALS_CANNOT_SIGN_REQUEST ) ; } return new CloudQueueClient ( this . getQueueStorageUri ( ) , this . getCredentials ( ) ) ; }

Creates a new Queue service client.

@return A client object that uses the Queue service endpoint.


public CloudTableClient createCloudTableClient() {
        if (this.getTableStorageUri() == null) {
            throw new IllegalArgumentException(SR.TABLE_ENDPOINT_NOT_CONFIGURED);
        }

        if (this.credentials == null) {
            throw new IllegalArgumentException(SR.MISSING_CREDENTIALS);
        }

        if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) {

            throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST);
        }

        return new CloudTableClient(this.getTableStorageUri(), this.getCredentials());
    }

public CloudTableClient createCloudTableClient ( ) { if ( this . getTableStorageUri ( ) == null ) { throw new IllegalArgumentException ( SR . TABLE_ENDPOINT_NOT_CONFIGURED ) ; } if ( this . credentials == null ) { throw new IllegalArgumentException ( SR . MISSING_CREDENTIALS ) ; } if ( ! StorageCredentialsHelper . canCredentialsGenerateClient ( this . credentials ) ) { throw new IllegalArgumentException ( SR . CREDENTIALS_CANNOT_SIGN_REQUEST ) ; } return new CloudTableClient ( this . getTableStorageUri ( ) , this . getCredentials ( ) ) ; }

Creates a new Table service client.

@return A client object that uses the Table service endpoint.


public String generateSharedAccessSignature(SharedAccessAccountPolicy policy)
            throws InvalidKeyException, StorageException {
        if (!StorageCredentialsHelper.canCredentialsSignRequest(this.getCredentials())) {
            throw new IllegalArgumentException(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
        }

        final String sig = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForAccount(
                this.credentials.getAccountName(), policy, this.getCredentials());
        final UriQueryBuilder sasBuilder =
                SharedAccessSignatureHelper.generateSharedAccessSignatureForAccount(policy, sig);
        return sasBuilder.toString();
    }

Returns a shared access signature for the account.

@param policy
A {@link SharedAccessAccountPolicy} specifying the access policy for the shared access signature.

@return The query string returned includes the leading question mark.
@throws StorageException
If a storage service error occurred.
@throws InvalidKeyException
If the key is invalid.

Returns a shared access signature for the account .


protected String generateRequestIdentity(boolean isSingleIndexEntry, final String entryName)
            throws StorageException {
        if (isSingleIndexEntry) {
            return String.format("'%s'", entryName.replace("'", "''"));
        }

        if (this.opType == TableOperationType.INSERT) {
            return Constants.EMPTY_STRING;
        }
        else {
            String pk = null;
            String rk = null;

            if (this.opType == TableOperationType.RETRIEVE) {
                final QueryTableOperation qOp = (QueryTableOperation) this;
                pk = qOp.getPartitionKey();
                rk = qOp.getRowKey();
            }
            else {
                pk = this.getEntity().getPartitionKey();
                rk = this.getEntity().getRowKey();
            }

            return String.format("%s='%s',%s='%s'",
                    TableConstants.PARTITION_KEY, pk.replace("'", "''"),
                    TableConstants.ROW_KEY, rk.replace("'", "''"));
        }
    }

protected String generateRequestIdentity ( boolean isSingleIndexEntry , final String entryName ) throws StorageException { if ( isSingleIndexEntry ) { return String . format ( "'%s'" , entryName . replace ( "'" , "''" ) ) ; } if ( this . opType == TableOperationType . INSERT ) { return Constants . EMPTY_STRING ; } else { String pk = null ; String rk = null ; if ( this . opType == TableOperationType . RETRIEVE ) { final QueryTableOperation qOp = ( QueryTableOperation ) this ; pk = qOp . getPartitionKey ( ) ; rk = qOp . getRowKey ( ) ; } else { pk = this . getEntity ( ) . getPartitionKey ( ) ; rk = this . getEntity ( ) . getRowKey ( ) ; } return String . format ( "%s='%s',%s='%s'" , TableConstants . PARTITION_KEY , pk . replace ( "'" , "''" ) , TableConstants . ROW_KEY , rk . replace ( "'" , "''" ) ) ; } }

Reserved for internal use. Generates the request identity, consisting of the specified entry name, or the
PartitionKey and RowKey pair from the operation, to identify the operation target.

@param isSingleIndexEntry
Pass true to use the specified entryName parameter, or false to
use PartitionKey and RowKey values from the operation as the request identity.
@param entryName
The entry name to use as the request identity if the isSingleIndexEntry parameter is
true.
@return
A String which represents the formatted request identity string.
@throws StorageException
If a storage service error occurred.

Reserved for internal use . Generates the request identity consisting of the specified entry name or the PartitionKey and RowKey pair from the operation to identify the operation target .


protected String generateRequestIdentityWithTable(final String tableName) throws StorageException {
        return String.format("%s(%s)", tableName, generateRequestIdentity(false, null));
    }

protected String generateRequestIdentityWithTable ( final String tableName ) throws StorageException { return String . format ( "%s(%s)" , tableName , generateRequestIdentity ( false , null ) ) ; }

Reserved for internal use. Generates the request identity string for the specified table. The request identity
string combines the table name with the PartitionKey and RowKey from the operation to identify specific table
entities. This request identity is already UrlEncoded.

@param tableName
A String which specifies the name of the table.
@return
A String which represents the formatted request identity string for the specified table.
@throws StorageException

Reserved for internal use . Generates the request identity string for the specified table . The request identity string combines the table name with the PartitionKey and RowKey from the operation to identify specific table entities . This request identity is already UrlEncoded .


protected final void initialize(OperationContext opContext) {
        RequestResult currResult = new RequestResult();
        this.setResult(currResult);
        opContext.appendRequestResult(currResult);

        this.setException(null);
        this.setNonExceptionedRetryableFailure(false);
        this.setIsSent(false);
    }

protected final void initialize ( OperationContext opContext ) { RequestResult currResult = new RequestResult ( ) ; this . setResult ( currResult ) ; opContext . appendRequestResult ( currResult ) ; this . setException ( null ) ; this . setNonExceptionedRetryableFailure ( false ) ; this . setIsSent ( false ) ; }

Resets the operation status flags between operations.

Resets the operation status flags between operations .


protected final StorageException materializeException(final OperationContext opContext) {
        if (this.getException() != null) {
            return this.getException();
        }

        return StorageException.translateException(this, null, opContext);
    }

protected final StorageException materializeException ( final OperationContext opContext ) { if ( this . getException ( ) != null ) { return this . getException ( ) ; } return StorageException . translateException ( this , null , opContext ) ; }

Returns either the held exception from the operation if it is set, otherwise the translated exception.

@param request
the reference to the HttpURLConnection for the operation.
@param opContext
an object used to track the execution of the operation
@return the exception to throw.

Returns either the held exception from the operation if it is set otherwise the translated exception .


public R postProcessResponse(HttpURLConnection connection, P parentObject, C client, OperationContext context,
            R storageObject) throws Exception {
        return storageObject;
    }

public R postProcessResponse ( HttpURLConnection connection , P parentObject , C client , OperationContext context , R storageObject ) throws Exception { return storageObject ; }

Post-Stream Retrieval function.

@param connection
HttpURLConnection configured for the operation.
@param storageObject
An object of the expected result's type.
@return the expected result of the operation.
@throws Exception


public StorageExtendedErrorInformation parseErrorDetails() {
        try {
            if (this.getConnection() == null || this.getConnection().getErrorStream() == null) {
                return null;
            }

            return StorageErrorHandler.getExtendedErrorInformation(this.getConnection().getErrorStream());
        } catch (final Exception e) {
            return null;
        }
    }

public StorageExtendedErrorInformation parseErrorDetails ( ) { try { if ( this . getConnection ( ) == null || this . getConnection ( ) . getErrorStream ( ) == null ) { return null ; } return StorageErrorHandler . getExtendedErrorInformation ( this . getConnection ( ) . getErrorStream ( ) ) ; } catch ( final Exception e ) { return null ; } }

Returns extended error information for this request.

@return A {@link StorageExtendedErrorInformation} object that represents the error details for the specified
request.

Returns extended error information for this request .


public void delete(final TableEntity entity) {
        this.lockToPartitionKey(entity.getPartitionKey());
        this.add(TableOperation.delete(entity));
    }

public void delete ( final TableEntity entity ) { this . lockToPartitionKey ( entity . getPartitionKey ( ) ) ; this . add ( TableOperation . delete ( entity ) ) ; }

Adds a table operation to delete the specified entity to the batch operation.

@param entity
The {@link TableEntity} to delete.

Adds a table operation to delete the specified entity to the batch operation .


public void insert(final TableEntity entity, boolean echoContent) {
        this.lockToPartitionKey(entity.getPartitionKey());
        this.add(TableOperation.insert(entity, echoContent));
    }

public void insert ( final TableEntity entity , boolean echoContent ) { this . lockToPartitionKey ( entity . getPartitionKey ( ) ) ; this . add ( TableOperation . insert ( entity , echoContent ) ) ; }

Adds a table operation to insert the specified entity to the batch operation.

@param entity
The {@link TableEntity} to insert.
@param echoContent
The boolean representing whether the message payload should be returned in the response.

Adds a table operation to insert the specified entity to the batch operation .


public void insertOrMerge(final TableEntity entity) {
        this.lockToPartitionKey(entity.getPartitionKey());
        this.add(TableOperation.insertOrMerge(entity));
    }

public void insertOrMerge ( final TableEntity entity ) { this . lockToPartitionKey ( entity . getPartitionKey ( ) ) ; this . add ( TableOperation . insertOrMerge ( entity ) ) ; }

Adds a table operation to insert or merge the specified entity to the batch operation.

@param entity
The {@link TableEntity} to insert if not found or to merge if it exists.

Adds a table operation to insert or merge the specified entity to the batch operation .


public void insertOrReplace(final TableEntity entity) {
        this.lockToPartitionKey(entity.getPartitionKey());
        this.add(TableOperation.insertOrReplace(entity));
    }

public void insertOrReplace ( final TableEntity entity ) { this . lockToPartitionKey ( entity . getPartitionKey ( ) ) ; this . add ( TableOperation . insertOrReplace ( entity ) ) ; }

Adds a table operation to insert or replace the specified entity to the batch operation.

@param entity
The {@link TableEntity} to insert if not found or to replace if it exists.

Adds a table operation to insert or replace the specified entity to the batch operation .


public void merge(final TableEntity entity) {
        this.lockToPartitionKey(entity.getPartitionKey());
        this.add(TableOperation.merge(entity));
    }

public void merge ( final TableEntity entity ) { this . lockToPartitionKey ( entity . getPartitionKey ( ) ) ; this . add ( TableOperation . merge ( entity ) ) ; }

Adds a table operation to merge the specified entity to the batch operation.

@param entity
The {@link TableEntity} to merge.

Adds a table operation to merge the specified entity to the batch operation .


@Override
    public TableOperation remove(int index) {
        TableOperation op = super.remove(index);
        checkResetEntityLocks();
        return op;
    }

@ Override public TableOperation remove ( int index ) { TableOperation op = super . remove ( index ) ; checkResetEntityLocks ( ) ; return op ; }

Removes the table operation at the specified index from the batch operation.

@param index
An int which represents the index in the ArrayList of the table operation to
remove from the batch operation.

Removes the table operation at the specified index from the batch operation .


@Override
    public boolean removeAll(java.util.Collection<?> c) {
        boolean ret = super.removeAll(c);
        checkResetEntityLocks();
        return ret;
    }

@ Override public boolean removeAll ( java . util . Collection < ? > c ) { boolean ret = super . removeAll ( c ) ; checkResetEntityLocks ( ) ; return ret ; }

Removes all elements of the specified collection from the batch operation.

@param c
The collection of elements to remove from the batch operation.
@return
true if the objects in the collection were removed successfully.

Removes all elements of the specified collection from the batch operation .


public void replace(final TableEntity entity) {
        this.lockToPartitionKey(entity.getPartitionKey());
        this.add(TableOperation.replace(entity));
    }

public void replace ( final TableEntity entity ) { this . lockToPartitionKey ( entity . getPartitionKey ( ) ) ; this . add ( TableOperation . replace ( entity ) ) ; }

Adds a table operation to replace the specified entity to the batch operation.

@param entity
The {@link TableEntity} to replace.

Adds a table operation to replace the specified entity to the batch operation .


private void checkSingleQueryPerBatch(final TableOperation op, final int size) {
        // if this has a query then no other operations can be added.
        if (this.hasQuery) {
            throw new IllegalArgumentException(SR.RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH);
        }

        if (op.getOperationType() == TableOperationType.RETRIEVE) {
            if (size > 0) {
                throw new IllegalArgumentException(SR.RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH);
            }
            else {
                this.hasQuery = true;
            }
        }

        this.containsWrites = op.getOperationType() != TableOperationType.RETRIEVE;
    }

Reserved for internal use. Verifies that the batch operation either contains no retrieve operations, or contains
only a single retrieve operation.

@param op
The {@link TableOperation} to be added if the verification succeeds.

Reserved for internal use . Verifies that the batch operation either contains no retrieve operations or contains only a single retrieve operation .


private void lockToPartitionKey(final String partitionKey) {
        if (this.partitionKey == null) {
            this.partitionKey = partitionKey;
        }
        else {
            if (partitionKey.length() != partitionKey.length() || !this.partitionKey.equals(partitionKey)) {
                throw new IllegalArgumentException(SR.OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY);
            }
        }
    }

Reserved for internal use. Verifies that the specified PartitionKey value matches the value in the batch
operation.

@param partitionKey
The String containing the PartitionKey value to check.

Reserved for internal use . Verifies that the specified PartitionKey value matches the value in the batch operation .


@DoesServiceRequest
    public void create(FileRequestOptions options, OperationContext opContext) throws StorageException {
        if (opContext == null) {
            opContext = new OperationContext();
        }

        assertNoSnapshot();
        if (this.properties != null && this.properties.getShareQuota() != null) {
            Utility.assertInBounds("Share Quota", this.properties.getShareQuota(), 1, FileConstants.MAX_SHARE_QUOTA);
        }

        opContext.initialize();
        options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient);

        ExecutionEngine.executeWithRetry(this.fileServiceClient, this, createImpl(options),
                options.getRetryPolicyFactory(), opContext);
    }

@
DoesServiceRequest
public
void
create
(
FileRequestOptions
options
,
OperationContext
opContext
)
throws
StorageException
{
if
(
opContext
==
)
{
opContext
=
new
OperationContext
(
)
;
}
assertNoSnapshot
(
)
;
if
(
this
.
properties
!=
&&
this
.
properties
.
getShareQuota
(
)
!=
)
{
Utility
.
assertInBounds
(
"Share Quota"
,
this
.
properties
.
getShareQuota
(
)
,
1
,
FileConstants
.
MAX_SHARE_QUOTA
)
;
}
opContext
.
initialize
(
)
;
options
=
FileRequestOptions
.
populateAndApplyDefaults
(
options
,
this
.
fileServiceClient
)
;
ExecutionEngine
.
executeWithRetry
(
this
.
fileServiceClient
,
this
,
createImpl
(
options
)
,
options
.
getRetryPolicyFactory
(
)
,
opContext
)
;
}

Creates the share using the specified options and operation context.

@param options
A {@link FileRequestOptions} object that specifies any additional options for the request. Specifying
null will use the default request options from the associated service client (
{@link CloudFileClient}).
@param opContext
An {@link OperationContext} object that represents the context for the current operation. This object
is used to track requests to the storage service, and to provide additional runtime information about
the operation.

@throws StorageException
If a storage service error occurred.

Creates the share using the specified options and operation context .


@DoesServiceRequest
    public boolean deleteIfExists(AccessCondition accessCondition, FileRequestOptions options,
            OperationContext opContext) throws StorageException {
        return this.deleteIfExists(DeleteShareSnapshotsOption.NONE, accessCondition, options, opContext);

    }

@ DoesServiceRequest public boolean deleteIfExists ( AccessCondition accessCondition , FileRequestOptions options , OperationContext opContext ) throws StorageException { return this . deleteIfExists ( DeleteShareSnapshotsOption . NONE , accessCondition , options , opContext ) ; }

Deletes the share if it exists using the specified request options and operation context.

@param accessCondition
An {@link AccessCondition} object that represents the access conditions for the share.
@param options
A {@link FileRequestOptions} object that specifies any additional options for the request. Specifying
null will use the default request options from the associated service client (
{@link CloudFileClient}).
@param opContext
An {@link OperationContext} object that represents the context for the current operation. This object
is used to track requests to the storage service, and to provide additional runtime information about
the operation.

@return true if the share existed and was deleted; otherwise, false.

@throws StorageException
If a storage service error occurred.

Deletes the share if it exists using the specified request options and operation context .


@DoesServiceRequest
    public FileSharePermissions downloadPermissions(AccessCondition accessCondition, FileRequestOptions options,
            OperationContext opContext) throws StorageException {
        if (opContext == null) {
            opContext = new OperationContext();
        }

        assertNoSnapshot();

        opContext.initialize();
        options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient);

        return ExecutionEngine.executeWithRetry(this.fileServiceClient, this,
                downloadPermissionsImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext);
    }

@ DoesServiceRequest public FileSharePermissions downloadPermissions ( AccessCondition accessCondition , FileRequestOptions options , OperationContext opContext ) throws StorageException { if ( opContext == null ) { opContext = new OperationContext ( ) ; } assertNoSnapshot ( ) ; opContext . initialize ( ) ; options = FileRequestOptions . populateAndApplyDefaults ( options , this . fileServiceClient ) ; return ExecutionEngine . executeWithRetry ( this . fileServiceClient , this , downloadPermissionsImpl ( accessCondition , options ) , options . getRetryPolicyFactory ( ) , opContext ) ; }

Downloads the permissions settings for the share using the specified request options and operation context.

@param accessCondition
An {@link AccessCondition} object that represents the access conditions for the share.
@param options
A {@link FileRequestOptions} object that specifies any additional options for the request. Specifying
null will use the default request options from the associated service client (
{@link CloudFileClient}).
@param opContext
An {@link OperationContext} object that represents the context for the current operation. This object
is used to track requests to the storage service, and to provide additional runtime information about
the operation.

@return A {@link FileSharePermissions} object that represents the share's permissions.

@throws StorageException
If a storage service error occurred.

Downloads the permissions settings for the share using the specified request options and operation context .


public String generateSharedAccessSignature(
            final SharedAccessFilePolicy policy, final String groupPolicyIdentifier, final IPRange ipRange,
            final SharedAccessProtocols protocols)
            throws InvalidKeyException, StorageException {

        if (!StorageCredentialsHelper.canCredentialsSignRequest(this.fileServiceClient.getCredentials())) {
            final String errorMessage = SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY;
            throw new IllegalArgumentException(errorMessage);
        }

        final String resourceName = this.getSharedAccessCanonicalName();

        final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForBlobAndFile(
                policy, null /* SharedAccessHeaders */, groupPolicyIdentifier, resourceName,
                ipRange, protocols, this.fileServiceClient);

        final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignatureForBlobAndFile(
                policy, null /* SharedAccessHeaders */, groupPolicyIdentifier, "s", ipRange, protocols, signature);

        return builder.toString();
    }

Returns a shared access signature for the share. Note this does not contain the leading "?".

@param policy
An {@link SharedAccessFilePolicy} object that represents the access policy for the
shared access signature.
@param groupPolicyIdentifier
A String which represents the share-level access policy.
@param ipRange
A {@link IPRange} object containing the range of allowed IP addresses.
@param protocols
A {@link SharedAccessProtocols} representing the allowed Internet protocols.

@return A String which represents a shared access signature for the share.

@throws StorageException
If a storage service error occurred.
@throws InvalidKeyException
If the key is invalid.

Returns a shared access signature for the share . Note this does not contain the leading ? .


@DoesServiceRequest
    public void uploadPermissions(final FileSharePermissions permissions) throws StorageException {
        this.uploadPermissions(permissions, null /* accessCondition */, null /* options */, null /* opContext */);
    }

@
DoesServiceRequest
public
void
uploadPermissions
(
final
FileSharePermissions
permissions
)
throws
StorageException
{
this
.
uploadPermissions
(
permissions
,
/* accessCondition */
,
/* options */
,
/* opContext */
)
;
}

Uploads the share's permissions.

@param permissions
A {@link FileSharePermissions} object that represents the permissions to upload.

@throws StorageException
If a storage service error occurred.


@DoesServiceRequest
    public void uploadPermissions(final FileSharePermissions permissions, final AccessCondition accessCondition,
            FileRequestOptions options, OperationContext opContext) throws StorageException {
        assertNoSnapshot();

        if (opContext == null) {
            opContext = new OperationContext();
        }

        opContext.initialize();
        options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient);

        ExecutionEngine.executeWithRetry(this.fileServiceClient, this,
                uploadPermissionsImpl(permissions, accessCondition, options), options.getRetryPolicyFactory(),
                opContext);
    }

@ DoesServiceRequest public void uploadPermissions ( final FileSharePermissions permissions , final AccessCondition accessCondition , FileRequestOptions options , OperationContext opContext ) throws StorageException { assertNoSnapshot ( ) ; if ( opContext == null ) { opContext = new OperationContext ( ) ; } opContext . initialize ( ) ; options = FileRequestOptions . populateAndApplyDefaults ( options , this . fileServiceClient ) ; ExecutionEngine . executeWithRetry ( this . fileServiceClient , this , uploadPermissionsImpl ( permissions , accessCondition , options ) , options . getRetryPolicyFactory ( ) , opContext ) ; }

Uploads the share's permissions using the specified request options and operation context.

@param permissions
A {@link FileSharePermissions} object that represents the permissions to upload.
@param accessCondition
An {@link AccessCondition} object that represents the access conditions for the share.
@param options
A {@link FileRequestOptions} object that specifies any additional options for the request. Specifying
null will use the default request options from the associated service client (
{@link CloudFileClient}).
@param opContext
An {@link OperationContext} object that represents the context for the current operation. This object
is used to track requests to the storage service, and to provide additional runtime information about
the operation.

@throws StorageException
If a storage service error occurred.

Uploads the share s permissions using the specified request options and operation context .


public final URI getQualifiedUri() throws URISyntaxException, StorageException {
        if (this.isSnapshot()) {
            return PathUtility.addToQuery(this.getUri(), String.format("sharesnapshot=%s", this.snapshotID));
        }

        return this.fileServiceClient.getCredentials().transformUri(this.getUri());
    }

public final URI getQualifiedUri ( ) throws URISyntaxException , StorageException { if ( this . isSnapshot ( ) ) { return PathUtility . addToQuery ( this . getUri ( ) , String . format ( "sharesnapshot=%s" , this . snapshotID ) ) ; } return this . fileServiceClient . getCredentials ( ) . transformUri ( this . getUri ( ) ) ; }

Returns the snapshot or shared access signature qualified URI for this share.

@return A java.net.URI object that represents the snapshot or shared access signature.

@throws StorageException
If a storage service error occurred.
@throws URISyntaxException
If the resource URI is invalid.

Returns the snapshot or shared access signature qualified URI for this share .


public void BasicInsertEntity() throws StorageException {
        // Note: the limitations on an insert operation are
        // - the serialized payload must be 1 MB or less
        // - up to 252 properties in addition to the partition key, row key and
        // timestamp. 255 properties in total
        // - the serialized payload of each property must be 64 KB or less

        // Create a new customer entity.
        CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
        customer1.setEmail("Walter@contoso.com");
        customer1.setPhoneNumber("425-555-0101");

        // Create an operation to add the new customer to the tablebasics table.
        TableOperation insertCustomer1 = TableOperation.insert(customer1);

        // Submit the operation to the table service.
        table.execute(insertCustomer1);
    }

Illustrates how to form and execute a single insert operation.

@throws StorageException

Illustrates how to form and execute a single insert operation .


public void BasicBatch() throws StorageException {
        // Note: the limitations on a batch operation are
        // - up to 100 operations
        // - all operations must share the same PartitionKey
        // - if a retrieve is used it can be the only operation in the batch
        // - the serialized batch payload must be 4 MB or less

        // Define a batch operation.
        TableBatchOperation batchOperation = new TableBatchOperation();

        // Create a customer entity to add to the table.
        CustomerEntity customer = new CustomerEntity("Smith", "Jeff");
        customer.setEmail("Jeff@contoso.com");
        customer.setPhoneNumber("425-555-0104");
        batchOperation.insert(customer);

        // Create another customer entity to add to the table.
        CustomerEntity customer2 = new CustomerEntity("Smith", "Ben");
        customer2.setEmail("Ben@contoso.com");
        customer2.setPhoneNumber("425-555-0102");
        batchOperation.insert(customer2);

        // Create a third customer entity to add to the table.
        CustomerEntity customer3 = new CustomerEntity("Smith", "Denise");
        customer3.setEmail("Denise@contoso.com");
        customer3.setPhoneNumber("425-555-0103");
        batchOperation.insert(customer3);

        // Execute the batch of operations on the "tablebasics" table.
        table.execute(batchOperation);
    }

Illustrates how to form and execute a batch operation.

@throws StorageException

Illustrates how to form and execute a batch operation .


public void BasicQuery() throws StorageException {
        // Retrieve a single entity.
        // Retrieve the entity with partition key of "Smith" and row key of
        // "Jeff".
        TableOperation retrieveSmithJeff = TableOperation.retrieve("Smith",
                "Jeff", CustomerEntity.class);

        // Submit the operation to the table service and get the specific
        // entity.
        @SuppressWarnings("unused")
        CustomerEntity specificEntity = table.execute(retrieveSmithJeff)
                .getResultAsType();

        // Retrieve all entities in a partition.
        // Create a filter condition where the partition key is "Smith".
        String partitionFilter = TableQuery.generateFilterCondition(
                "PartitionKey", QueryComparisons.EQUAL, "Smith");

        // Specify a partition query, using "Smith" as the partition key filter.
        TableQuery<CustomerEntity> partitionQuery = TableQuery.from(
                CustomerEntity.class).where(partitionFilter);

        // Loop through the results, displaying information about the entity.
        for (CustomerEntity entity : table.execute(partitionQuery)) {
            act.outputText(
                    view,
                    entity.getPartitionKey() + " " + entity.getRowKey() + "\t"
                            + entity.getEmail() + "\t"
                            + entity.getPhoneNumber());
        }
    }

Illustrates how to form and execute a query operation.

@throws StorageException

Illustrates how to form and execute a query operation .


public void BasicUpsert() throws StorageException {
        // Retrieve the entity with partition key of "Smith" and row key of
        // "Jeff".
        TableOperation retrieveSmithJeff = TableOperation.retrieve("Smith",
                "Jeff", CustomerEntity.class);

        // Submit the operation to the table service and get the specific
        // entity.
        CustomerEntity specificEntity = table.execute(retrieveSmithJeff)
                .getResultAsType();

        // Specify a new phone number.
        specificEntity.setPhoneNumber("425-555-0105");

        // Create an operation to replace the entity.
        TableOperation replaceEntity = TableOperation.merge(specificEntity);

        // Submit the operation to the table service.
        table.execute(replaceEntity);
    }

Illustrates how to form and execute an upsert operation.

@throws StorageException

Illustrates how to form and execute an upsert operation .


public void BasicDeleteEntity() throws StorageException {
        // Create an operation to retrieve the entity with partition key of
        // "Smith" and row key of "Jeff".
        TableOperation retrieveSmithJeff = TableOperation.retrieve("Smith",
                "Jeff", CustomerEntity.class);

        // Retrieve the entity with partition key of "Smith" and row key of
        // "Jeff".
        CustomerEntity entitySmithJeff = table.execute(retrieveSmithJeff)
                .getResultAsType();

        // Create an operation to delete the entity.
        TableOperation deleteSmithJeff = TableOperation.delete(entitySmithJeff);

        // Submit the delete operation to the table service.
        table.execute(deleteSmithJeff);
    }

Illustrates how to form and execute an entity delete operation.

@throws StorageException

Illustrates how to form and execute an entity delete operation .


public void BasicListing() {
        // List the tables with a given prefix.
        Iterable<String> listTables = tableClient.listTables(tableName, null,
                null);
        for (String s : listTables) {
            act.outputText(view, String.format("List of tables: %s", s));
        }
    }

public
void
BasicListing
(
)
{
// List the tables with a given prefix.
Iterable
<
String
>
listTables
=
tableClient
.
listTables
(
tableName
,
,
)
;
for
(
String
s
:
listTables
)
{
act
.
outputText
(
view
,
String
.
format
(
"List of tables: %s"
,
s
)
)
;
}
}


private TableQuery<TableServiceEntity> generateListTablesQuery(final String prefix) {
        TableQuery<TableServiceEntity> listQuery = TableQuery.<TableServiceEntity> from(TableServiceEntity.class);
        listQuery.setSourceTableName(TableConstants.TABLES_SERVICE_TABLES_NAME);

        if (!Utility.isNullOrEmpty(prefix)) {
            // Append Max char to end '{' is 1 + 'z' in AsciiTable > uppperBound = prefix + '{'
            final String prefixFilter = String.format("(%s ge '%s') and (%s lt '%s{')", TableConstants.TABLE_NAME,
                    prefix, TableConstants.TABLE_NAME, prefix);

            listQuery = listQuery.where(prefixFilter);
        }

        return listQuery;
    }

Reserved for internal use. Generates a query to list table names with the given prefix.

@param prefix
A String containing the prefix to match on table names to return.
@return
A {@link TableQuery} instance for listing table names with the specified prefix.

Reserved for internal use . Generates a query to list table names with the given prefix .


protected <T extends TableEntity, R> ResultSegment<?> executeQuerySegmentedImpl(final TableQuery<T> queryToExecute,
            final EntityResolver<R> resolver, final ResultContinuation continuationToken, TableRequestOptions options,
            OperationContext opContext) throws StorageException {
        if (opContext == null) {
            opContext = new OperationContext();
        }

        opContext.initialize();
        options = TableRequestOptions.populateAndApplyDefaults(options, this);

        Utility.assertContinuationType(continuationToken, ResultContinuationType.TABLE);

        SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest();
        segmentedRequest.setToken(continuationToken);

        return ExecutionEngine.executeWithRetry(this, queryToExecute,
                this.executeQuerySegmentedWithResolverCoreImpl(queryToExecute, resolver, options, segmentedRequest),
                options.getRetryPolicyFactory(), opContext);
    }

Reserved for internal use. Executes a segmented query operation using the specified retry and timeout policies.

@param queryToExecute
The {@link TableQuery} to execute.
@param resolver
An {@link EntityResolver} instance which creates a projection of the table query result entities into
the specified type R. Pass null to return the results as the table entity
type.
@param continuationToken
The {@link ResultContinuation} to pass with the operation to resume a query, if any. Pass
null for an initial query.
@param options
A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout
settings for the operation. Specify null to use the request options specified on the
{@link CloudTableClient}.
@param opContext
An {@link OperationContext} object for tracking the current operation. Specify null to
safely ignore operation context.
@return
A {@link ResultSegment} containing a collection of the query results specialized for the
{@link TableEntity} or {@link EntityResolver} type returned by the query.
@throws StorageException
if a Storage service error occurs.

Reserved for internal use . Executes a segmented query operation using the specified retry and timeout policies .


protected <T extends TableEntity, R> Iterable<?> generateIteratorForQuery(final TableQuery<T> queryRef,
            final EntityResolver<R> resolver, TableRequestOptions options, OperationContext opContext) {

        if (opContext == null) {
            opContext = new OperationContext();
        }

        opContext.initialize();
        options = TableRequestOptions.populateAndApplyDefaults(options, this);

        SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest();

        if (resolver == null) {
            return new LazySegmentedIterable<CloudTableClient, TableQuery<T>, T>(this.executeQuerySegmentedCoreImpl(
                    queryRef, resolver, options, segmentedRequest), this, queryRef, options.getRetryPolicyFactory(),
                    opContext);
        }
        else {
            return new LazySegmentedIterable<CloudTableClient, TableQuery<T>, R>(
                    this.executeQuerySegmentedWithResolverCoreImpl(queryRef, resolver, options, segmentedRequest),
                    this, queryRef, options.getRetryPolicyFactory(), opContext);
        }
    }

Reserved for internal use. Generates an iterator for a segmented query operation.

@param queryRef
The {@link TableQuery} to execute.
@param resolver
An {@link EntityResolver} instance which creates a projection of the table query result entities into
the specified type R. Pass null to return the results as the table entity
type.
@param options
A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout
settings for the operation. Specify null to use the request options specified on the
{@link CloudTableClient}.
@param opContext
An {@link OperationContext} object for tracking the current operation. Specify null to
safely ignore operation context.
@return
An instance of Iterable specialized for the {@link TableEntity} or {@link EntityResolver}
type returned by the query.

Reserved for internal use . Generates an iterator for a segmented query operation .


private void populateVersion1Log(LogRecordStreamReader reader) throws IOException, ParseException,
            URISyntaxException {
        this.requestStartTime = reader.readDate(LogRecord.REQUEST_START_TIME_FORMAT);
        this.operationType = reader.readString();
        this.requestStatus = reader.readString();
        this.httpStatusCode = reader.readString();
        this.endToEndLatencyInMS = reader.readInteger();
        this.serverLatencyInMS = reader.readInteger();
        this.authenticationType = reader.readString();
        this.requesterAccountName = reader.readString();
        this.ownerAccountName = reader.readString();
        this.serviceType = reader.readString();
        this.requestUrl = reader.readUri();
        this.requestedObjectKey = reader.readQuotedString();
        this.requestIdHeader = reader.readUuid();
        this.operationCount = reader.readInteger();
        this.requesterIPAddress = reader.readString();
        this.requestVersionHeader = reader.readString();
        this.requestHeaderSize = reader.readLong();
        this.requestPacketSize = reader.readLong();
        this.responseHeaderSize = reader.readLong();
        this.responsePacketSize = reader.readLong();
        this.requestContentLength = reader.readLong();
        this.requestMD5 = reader.readQuotedString();
        this.serverMD5 = reader.readQuotedString();
        this.eTagIdentifier = reader.readQuotedString();
        this.lastModifiedTime = reader.readDate(LogRecord.LAST_MODIFIED_TIME_FORMAT);
        this.conditionsUsed = reader.readQuotedString();
        this.userAgentHeader = reader.readQuotedString();
        this.referrerHeader = reader.readQuotedString();
        this.clientRequestId = reader.readQuotedString();
        reader.endCurrentRecord();

    }

private void populateVersion1Log ( LogRecordStreamReader reader ) throws IOException , ParseException , URISyntaxException { this . requestStartTime = reader . readDate ( LogRecord . REQUEST_START_TIME_FORMAT ) ; this . operationType = reader . readString ( ) ; this . requestStatus = reader . readString ( ) ; this . httpStatusCode = reader . readString ( ) ; this . endToEndLatencyInMS = reader . readInteger ( ) ; this . serverLatencyInMS = reader . readInteger ( ) ; this . authenticationType = reader . readString ( ) ; this . requesterAccountName = reader . readString ( ) ; this . ownerAccountName = reader . readString ( ) ; this . serviceType = reader . readString ( ) ; this . requestUrl = reader . readUri ( ) ; this . requestedObjectKey = reader . readQuotedString ( ) ; this . requestIdHeader = reader . readUuid ( ) ; this . operationCount = reader . readInteger ( ) ; this . requesterIPAddress = reader . readString ( ) ; this . requestVersionHeader = reader . readString ( ) ; this . requestHeaderSize = reader . readLong ( ) ; this . requestPacketSize = reader . readLong ( ) ; this . responseHeaderSize = reader . readLong ( ) ; this . responsePacketSize = reader . readLong ( ) ; this . requestContentLength = reader . readLong ( ) ; this . requestMD5 = reader . readQuotedString ( ) ; this . serverMD5 = reader . readQuotedString ( ) ; this . eTagIdentifier = reader . readQuotedString ( ) ; this . lastModifiedTime = reader . readDate ( LogRecord . LAST_MODIFIED_TIME_FORMAT ) ; this . conditionsUsed = reader . readQuotedString ( ) ; this . userAgentHeader = reader . readQuotedString ( ) ; this . referrerHeader = reader . readQuotedString ( ) ; this . clientRequestId = reader . readQuotedString ( ) ; reader . endCurrentRecord ( ) ; }

Populates a LogRecord using the Version 1.0 schema and the given LogRecordStreamReader.

@param reader
the LogRecordStreamReader to use to populate the LogRecord.
@throws IOException
@throws ParseException
@throws URISyntaxException

Populates a LogRecord using the Version 1 . 0 schema and the given LogRecordStreamReader .


public static ListResponse<CloudQueue> getQueues(final InputStream stream, final CloudQueueClient serviceClient)
            throws SAXException, IOException, ParserConfigurationException {
        SAXParser saxParser = Utility.getSAXParser();
        QueueListHandler handler = new QueueListHandler(serviceClient);
        saxParser.parse(stream, handler);

        return handler.response;
    }

public static ListResponse < CloudQueue > getQueues ( final InputStream stream , final CloudQueueClient serviceClient ) throws SAXException , IOException , ParserConfigurationException { SAXParser saxParser = Utility . getSAXParser ( ) ; QueueListHandler handler = new QueueListHandler ( serviceClient ) ; saxParser . parse ( stream , handler ) ; return handler . response ; }

Parses the input stream containing the response body of the list queues request result and populates the class
data.

@param stream
The InputStream object to deserialize from.
@param serviceClient
A {@link CloudQueueClient} object associated with the storage
service.

@throws IOException
@throws SAXException
@throws ParserConfigurationException

Parses the input stream containing the response body of the list queues request result and populates the class data .


protected static StorageException translateFromHttpStatus(final int statusCode, final String statusDescription,
            final Exception inner) {
        String errorCode;
        switch (statusCode) {
        case HttpURLConnection.HTTP_FORBIDDEN:
            errorCode = StorageErrorCode.ACCESS_DENIED.toString();
            break;
        case HttpURLConnection.HTTP_GONE:
        case HttpURLConnection.HTTP_NOT_FOUND:
            errorCode = StorageErrorCode.RESOURCE_NOT_FOUND.toString();
            break;
        case 416:
        case HttpURLConnection.HTTP_BAD_REQUEST:
            // 416: RequestedRangeNotSatisfiable - No corresponding enum in HttpURLConnection
            errorCode = StorageErrorCode.BAD_REQUEST.toString();
            break;

        case HttpURLConnection.HTTP_PRECON_FAILED:
        case HttpURLConnection.HTTP_NOT_MODIFIED:
            errorCode = StorageErrorCode.CONDITION_FAILED.toString();
            break;

        case HttpURLConnection.HTTP_CONFLICT:
            errorCode = StorageErrorCode.RESOURCE_ALREADY_EXISTS.toString();
            break;

        case HttpURLConnection.HTTP_UNAVAILABLE:
            errorCode = StorageErrorCode.SERVER_BUSY.toString();
            break;

        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
            errorCode = StorageErrorCode.SERVICE_TIMEOUT.toString();
            break;

        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            errorCode = StorageErrorCode.SERVICE_INTERNAL_ERROR.toString();
            break;

        case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
            errorCode = StorageErrorCode.NOT_IMPLEMENTED.toString();
            break;

        case HttpURLConnection.HTTP_BAD_GATEWAY:
            errorCode = StorageErrorCode.BAD_GATEWAY.toString();
            break;

        case HttpURLConnection.HTTP_VERSION:
            errorCode = StorageErrorCode.HTTP_VERSION_NOT_SUPPORTED.toString();
            break;
        default:
            errorCode = null;
        }

        if (errorCode == null) {
            return null;
        } else {
            return new StorageException(errorCode, statusDescription, statusCode, null, inner);
        }
    }

Translates the specified HTTP status code into a storage exception.

@param statusCode
The HTTP status code returned by the operation.
@param statusDescription
A String that represents the status description.
@param inner
An Exception object that represents a reference to the initial exception, if one exists.

@return A StorageException object that represents translated exception.

Translates the specified HTTP status code into a storage exception .


@DoesServiceRequest
    public Iterable<CloudQueue> listQueues() {
        return this.listQueues(null, QueueListingDetails.NONE, null, null);
    }

@ DoesServiceRequest public Iterable < CloudQueue > listQueues ( ) { return this . listQueues ( null , QueueListingDetails . NONE , null , null ) ; }

Gets an iterable collection of queues for this queue service client.

@return An iterable collection of {@link CloudQueue} objects retrieved lazily that
represent the queues in this client.

Gets an iterable collection of queues for this queue service client .


@DoesServiceRequest
    public Iterable<CloudQueue> listQueues(final String prefix) {
        return this.listQueues(prefix, QueueListingDetails.NONE, null, null);
    }

@ DoesServiceRequest public Iterable < CloudQueue > listQueues ( final String prefix ) { return this . listQueues ( prefix , QueueListingDetails . NONE , null , null ) ; }

Returns an iterable collection of queues whose names begin with the
specified prefix in this Queue service client.

@param prefix
A String that represents the queue name prefix.

@return An iterable collection of {@link CloudQueue} objects retrieved lazily that
represent the queues in this client whose names begin with the
specified prefix.

Returns an iterable collection of queues whose names begin with the specified prefix in this Queue service client .


@DoesServiceRequest
    public Iterable<CloudQueue> listQueues(final String prefix, final QueueListingDetails detailsIncluded,
            QueueRequestOptions options, OperationContext opContext) {
        if (opContext == null) {
            opContext = new OperationContext();
        }

        opContext.initialize();
        options = QueueRequestOptions.populateAndApplyDefaults(options, this);

        SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest();
        return new LazySegmentedIterable<CloudQueueClient, Void, CloudQueue>(this.listQueuesSegmentedImpl(prefix,
                detailsIncluded, null, options, segmentedRequest), this, null, options.getRetryPolicyFactory(), opContext);
    }

@ DoesServiceRequest public Iterable < CloudQueue > listQueues ( final String prefix , final QueueListingDetails detailsIncluded , QueueRequestOptions options , OperationContext opContext ) { if ( opContext == null ) { opContext = new OperationContext ( ) ; } opContext . initialize ( ) ; options = QueueRequestOptions . populateAndApplyDefaults ( options , this ) ; SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest ( ) ; return new LazySegmentedIterable < CloudQueueClient , Void , CloudQueue > ( this . listQueuesSegmentedImpl ( prefix , detailsIncluded , null , options , segmentedRequest ) , this , null , options . getRetryPolicyFactory ( ) , opContext ) ; }

Returns an iterable collection of queues whose names begin with the
specified prefix for this Queue service client, using the specified
details setting, request options, and operation context.

@param prefix
A String that represents the queue name prefix.
@param detailsIncluded
A {@link QueueListingDetails} value that indicates whether
queue metadata will be returned.
@param options
A {@link QueueRequestOptions} object that specifies any
additional options for the request. Specifying null will use the default request options
from
the associated service client ( {@link CloudQueue}).
@param opContext
An {@link OperationContext} object that represents the context
for the current operation. This object is used to track
requests to the storage service, and to provide additional
runtime information about the operation.

@return An iterable collection of {@link CloudQueue} objects retrieved lazily that
represents the specified queues for this client.

Returns an iterable collection of queues whose names begin with the specified prefix for this Queue service client using the specified details setting request options and operation context .


@DoesServiceRequest
    public ResultSegment<CloudQueue> listQueuesSegmented() throws StorageException {
        return this.listQueuesSegmented(null, QueueListingDetails.NONE, null, null, null, null);
    }

@ DoesServiceRequest public ResultSegment < CloudQueue > listQueuesSegmented ( ) throws StorageException { return this . listQueuesSegmented ( null , QueueListingDetails . NONE , null , null , null , null ) ; }

Gets a result segment of an iterable collection of queues for this Queue
service client.

@return A {@link ResultSegment} of {@link CloudQueue} objects that
contains a segment of the iterable collection of {@link CloudQueue} objects that represent the requested
queues in
the storage service.

@throws StorageException
If a storage service error occurred during the operation.

Gets a result segment of an iterable collection of queues for this Queue service client .


@DoesServiceRequest
    public ResultSegment<CloudQueue> listQueuesSegmented(final String prefix,
            final QueueListingDetails detailsIncluded, final Integer maxResults,
            final ResultContinuation continuationToken, QueueRequestOptions options, OperationContext opContext)
            throws StorageException {

        if (opContext == null) {
            opContext = new OperationContext();
        }

        opContext.initialize();
        options = QueueRequestOptions.populateAndApplyDefaults(options, this);

        SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest();
        segmentedRequest.setToken(continuationToken);
        return ExecutionEngine.executeWithRetry(this, null,
                this.listQueuesSegmentedImpl(prefix, detailsIncluded, maxResults, options, segmentedRequest),
                options.getRetryPolicyFactory(), opContext);
    }

@ DoesServiceRequest public ResultSegment < CloudQueue > listQueuesSegmented ( final String prefix , final QueueListingDetails detailsIncluded , final Integer maxResults , final ResultContinuation continuationToken , QueueRequestOptions options , OperationContext opContext ) throws StorageException { if ( opContext == null ) { opContext = new OperationContext ( ) ; } opContext . initialize ( ) ; options = QueueRequestOptions . populateAndApplyDefaults ( options , this ) ; SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest ( ) ; segmentedRequest . setToken ( continuationToken ) ; return ExecutionEngine . executeWithRetry ( this , null , this . listQueuesSegmentedImpl ( prefix , detailsIncluded , maxResults , options , segmentedRequest ) , options . getRetryPolicyFactory ( ) , opContext ) ; }

Gets a result segment of an iterable collection of queues whose names
begin with the specified prefix for this queue, using the specified
listing details options, request options, and operation context.

@param prefix
A String that represents the prefix of the queue
name to match.
@param detailsIncluded
A {@link QueueListingDetails} value that indicates whether
queue metadata will be returned.
@param maxResults
The maximum number of results to retrieve.  If null or greater
than 5000, the server will return up to 5,000 items.  Must be at least 1.
@param continuationToken
A {@link ResultContinuation} object that represents a
continuation token returned by a previous listing operation.
@param options
A {@link QueueRequestOptions} object that specifies any additional options for
the request. Specifying null will use the default request options
from the associated service client ( {@link CloudQueue}).
@param opContext
An {@link OperationContext} object that represents the context
for the current operation. This object is used to track
requests to the storage service, and to provide additional
runtime information about the operation.

@return A {@link ResultSegment} of {@link CloudQueue} objects that contains a segment of
the iterable collection of {@link CloudQueue} objects that represent the requested
queues in the storage service.

@throws StorageException
If a storage service error occurred during the operation.

Gets a result segment of an iterable collection of queues whose names begin with the specified prefix for this queue using the specified listing details options request options and operation context .


public void addConfiguredXMLCatalog (@Nonnull final XMLCatalog aXmlCatalog)
  {
    m_aXmlCatalog.addConfiguredXMLCatalog (aXmlCatalog);
    log ("Added XMLCatalog " + aXmlCatalog, Project.MSG_DEBUG);
  }

public
void
addConfiguredXMLCatalog
(
@
Nonnull
final
XMLCatalog
aXmlCatalog
)
{
m_aXmlCatalog
.
addConfiguredXMLCatalog
(
aXmlCatalog
)
;
log
(
"Added XMLCatalog "
+
aXmlCatalog
,
Project
.
MSG_DEBUG
)
;
}

Add the catalog to our internal catalog

@param aXmlCatalog
the XMLCatalog instance to use to look up DTDs


@Nullable
  public String getUniqueID (@Nullable final String sID)
  {
    if (sID == null)
      return null;

    if (m_aUsedIDs.add (sID))
    {
      // Unique ID
      return sID;
    }

    // Non-unique ID
    int nIndex = 0;
    String sNewID = sID + nIndex;
    do
    {
      if (m_aUsedIDs.add (sNewID))
      {
        // Now it's unique
        return sNewID;
      }
      ++nIndex;
      sNewID = sID + nIndex;
    } while (true);
  }

@
Nullable
public
String
getUniqueID
(
@
Nullable
final
String
sID
)
{
if
(
sID
==
)
return
;
if
(
m_aUsedIDs
.
add
(
sID
)
)
{
// Unique ID
return
sID
;
}
// Non-unique ID
int
nIndex
=
0
;
String
sNewID
=
sID
+
nIndex
;
do
{
if
(
m_aUsedIDs
.
add
(
sNewID
)
)
{
// Now it's unique
return
sNewID
;
}
++
nIndex
;
sNewID
=
sID
+
nIndex
;
}
while
(
true
)
;
}

Create a unique ID based on the passed one. If the passed ID is not yet
contained, than a numeric index is appended until the ID is unique.

@param sID
The source ID. May be null.
@return null if the passed ID is null indicating
that no ID is present. Otherwise a unique ID is returned.

Create a unique ID based on the passed one . If the passed ID is not yet contained than a numeric index is appended until the ID is unique .


@Nonnull
  public SchematronResourcePure setPhase (@Nullable final String sPhase)
  {
    if (m_aBoundSchema != null)
      throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!");
    m_sPhase = sPhase;
    return this;
  }

Set the Schematron phase to be evaluated. Changing the phase will result in
a newly bound schema!

@param sPhase
The name of the phase to use. May be null which means
all phases.
@return this

Set the Schematron phase to be evaluated . Changing the phase will result in a newly bound schema!


@Nonnull
  public SchematronResourcePure setErrorHandler (@Nullable final IPSErrorHandler aErrorHandler)
  {
    if (m_aBoundSchema != null)
      throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!");
    m_aErrorHandler = aErrorHandler;
    return this;
  }

Set the error handler to be used during binding.

@param aErrorHandler
The error handler. May be null.
@return this

Set the error handler to be used during binding .


@Nonnull
  public SchematronResourcePure setVariableResolver (@Nullable final XPathVariableResolver aVariableResolver)
  {
    if (m_aBoundSchema != null)
      throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!");
    m_aVariableResolver = aVariableResolver;
    return this;
  }

Set the variable resolver to be used in the XPath statements. This can only
be set before the Schematron is bound. If it is already bound an exception
is thrown to indicate the unnecessity of the call.

@param aVariableResolver
The variable resolver to set. May be null.
@return this

Set the variable resolver to be used in the XPath statements . This can only be set before the Schematron is bound . If it is already bound an exception is thrown to indicate the unnecessity of the call .