private static List<String> splitToList(String str, String delimiter) {
        ArrayList<String> list = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(str, delimiter);
        while (st.hasMoreElements()) {
            list.add(st.nextToken());
        }
        return list;
    }

private static List < String > splitToList ( String str , String delimiter ) { ArrayList < String > list = new ArrayList < String > ( ) ; StringTokenizer st = new StringTokenizer ( str , delimiter ) ; while ( st . hasMoreElements ( ) ) { list . add ( st . nextToken ( ) ) ; } return list ; }

Split a delimiter separated string into an ArrayList

@param str
the string to split
@param delimiter
the character to split on
@return the list of strings


private static EnumSet<CorsHttpMethods> splitToEnumSet(String str, String delimiter) {
        EnumSet<CorsHttpMethods> set = EnumSet.noneOf(CorsHttpMethods.class);
        StringTokenizer st = new StringTokenizer(str, delimiter);
        while (st.hasMoreElements()) {
            set.add(CorsHttpMethods.valueOf(st.nextToken()));
        }
        return set;
    }

private static EnumSet < CorsHttpMethods > splitToEnumSet ( String str , String delimiter ) { EnumSet < CorsHttpMethods > set = EnumSet . noneOf ( CorsHttpMethods . class ) ; StringTokenizer st = new StringTokenizer ( str , delimiter ) ; while ( st . hasMoreElements ( ) ) { set . add ( CorsHttpMethods . valueOf ( st . nextToken ( ) ) ) ; } return set ; }

Split a delimiter separated string into a EnumSet of CorsHttpMethods

@param str
the string to split
@param delimiter
the character to split on
@return the set of CorsHttpMethods


public synchronized void updateKey(final byte[] key) {
        if (key == null || key.length == 0) {
            throw new IllegalArgumentException(SR.INVALID_KEY);
        }

        this.key = key;
        this.hmacSha256 = null;
    }

public synchronized void updateKey ( final byte [ ] key ) { if ( key == null || key . length == 0 ) { throw new IllegalArgumentException ( SR . INVALID_KEY ) ; } this . key = key ; this . hmacSha256 = null ; }

Sets the name of the access key to be used when signing the request.

@param key
A String that represents the name of the access key to be used when signing the request.

Sets the name of the access key to be used when signing the request .


public synchronized Mac getHmac256() throws InvalidKeyException {
        if (this.hmacSha256 == null) {
            // Initializes the HMAC-SHA256 Mac and SecretKey.
            try {
                this.hmacSha256 = Mac.getInstance("HmacSHA256");
            }
            catch (final NoSuchAlgorithmException e) {
                throw new IllegalArgumentException();
            }
            this.hmacSha256.init(new SecretKeySpec(this.key, "HmacSHA256"));
        }
        return this.hmacSha256;
    }

Gets the HmacSha256 associated with the account key.

@return A MAC created with the account key.

@throws InvalidKeyException
If the key is not a valid storage key.

Gets the HmacSha256 associated with the account key .


private static void validateIPAddress(String ipAddress) {
        try {
            @SuppressWarnings("unused")
            Inet4Address address = (Inet4Address) Inet4Address.getByName(ipAddress);
        }
        catch (Exception ex) {
            throw new IllegalArgumentException(String.format(SR.INVALID_IP_ADDRESS, ipAddress), ex);
        }
    }

private static void validateIPAddress ( String ipAddress ) { try { @ SuppressWarnings ( "unused" ) Inet4Address address = ( Inet4Address ) Inet4Address . getByName ( ipAddress ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( String . format ( SR . INVALID_IP_ADDRESS , ipAddress ) , ex ) ; } }

Validate that the IP address is IPv4.

@param ipAddress
the IP address to validate


public static byte[] decode(final String data) {
        if (data == null) {
            throw new IllegalArgumentException(SR.STRING_NOT_VALID);
        }

        int byteArrayLength = 3 * data.length() / 4;

        if (data.endsWith("==")) {
            byteArrayLength -= 2;
        }
        else if (data.endsWith("=")) {
            byteArrayLength -= 1;
        }

        final byte[] retArray = new byte[byteArrayLength];
        int byteDex = 0;
        int charDex = 0;

        for (; charDex < data.length(); charDex += 4) {
            // get 4 chars, convert to 3 bytes
            final int char1 = DECODE_64[(byte) data.charAt(charDex)];
            final int char2 = DECODE_64[(byte) data.charAt(charDex + 1)];
            final int char3 = DECODE_64[(byte) data.charAt(charDex + 2)];
            final int char4 = DECODE_64[(byte) data.charAt(charDex + 3)];

            if (char1 < 0 || char2 < 0 || char3 == -1 || char4 == -1) {
                // invalid character(-1), or bad padding (-2)
                throw new IllegalArgumentException(SR.STRING_NOT_VALID);
            }

            int tVal = char1 << 18;
            tVal += char2 << 12;
            tVal += (char3 & 0xff) << 6;
            tVal += char4 & 0xff;

            if (char3 == -2) {
                // two "==" pad chars, check bits 12-24
                tVal &= 0x00FFF000;
                retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
            }
            else if (char4 == -2) {
                // one pad char "=" , check bits 6-24.
                tVal &= 0x00FFFFC0;
                retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
                retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF);

            }
            else {
                // No pads take all 3 bytes, bits 0-24
                retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF);
                retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF);
                retArray[byteDex++] = (byte) (tVal & 0xFF);
            }
        }
        return retArray;
    }

Decodes a given Base64 string into its corresponding byte array.

@param data
the Base64 string, as a String object, to decode

@return the corresponding decoded byte array
@throws IllegalArgumentException
If the string is not a valid base64 encoded string

Decodes a given Base64 string into its corresponding byte array .


public static String encode(final Byte[] data) {
        final StringBuilder builder = new StringBuilder();
        final int dataRemainder = data.length % 3;

        int j = 0;
        int n = 0;
        for (; j < data.length; j += 3) {

            if (j < data.length - dataRemainder) {
                n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8) + (data[j + 2] & 0xFF);
            }
            else {
                if (dataRemainder == 1) {
                    n = (data[j] & 0xFF) << 16;
                }
                else if (dataRemainder == 2) {
                    n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8);
                }
            }

            // Left here for readability
            // byte char1 = (byte) ((n >>> 18) & 0x3F);
            // byte char2 = (byte) ((n >>> 12) & 0x3F);
            // byte char3 = (byte) ((n >>> 6) & 0x3F);
            // byte char4 = (byte) (n & 0x3F);
            builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 18) & 0x3F)));
            builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 12) & 0x3F)));
            builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 6) & 0x3F)));
            builder.append(BASE_64_CHARS.charAt((byte) (n & 0x3F)));
        }

        final int bLength = builder.length();

        // append '=' to pad
        if (data.length % 3 == 1) {
            builder.replace(bLength - 2, bLength, "==");
        }
        else if (data.length % 3 == 2) {
            builder.replace(bLength - 1, bLength, "=");
        }

        return builder.toString();
    }

Encodes a byte array as a Base64 string.

@param data
the byte array to encode
@return the Base64-encoded string, as a String object

Encodes a byte array as a Base64 string .


public static boolean validateIsBase64String(final String data) {

        if (data == null || data.length() % 4 != 0) {
            return false;
        }

        for (int m = 0; m < data.length(); m++) {
            final byte charByte = (byte) data.charAt(m);

            // pad char detected
            if (DECODE_64[charByte] == -2) {
                if (m < data.length() - 2) {
                    return false;
                }
                else if (m == data.length() - 2 && DECODE_64[(byte) data.charAt(m + 1)] != -2) {
                    return false;
                }
            }

            if (charByte < 0 || DECODE_64[charByte] == -1) {
                return false;
            }
        }

        return true;
    }

public
static
boolean
validateIsBase64String
(
final
String
data
)
{
if
(
data
==
||
data
.
length
(
)
%
4
!=
0
)
{
return
false
;
}
for
(
int
m
=
0
;
m
<
data
.
length
(
)
;
m
++
)
{
final
byte
charByte
=
(
byte
)
data
.
charAt
(
m
)
;
// pad char detected
if
(
DECODE_64
[
charByte
]
==
2
)
{
if
(
m
<
data
.
length
(
)
2
)
{
return
false
;
}
else
if
(
m
==
data
.
length
(
)
2
&&
DECODE_64
[
(
byte
)
data
.
charAt
(
m
+
1
)
]
!=
2
)
{
return
false
;
}
}
if
(
charByte
<
0
||
DECODE_64
[
charByte
]
==
1
)
{
return
false
;
}
}
return
true
;
}

Determines whether the given string contains only Base64 characters.

@param data
the string, as a String object, to validate
@return true if data is a valid Base64 string, otherwise false

Determines whether the given string contains only Base64 characters .


public static void validateContainerName(String containerName) {
		if (!("$root".equals(containerName) || "$logs".equals(containerName))) {
			NameValidator.validateShareContainerQueueHelper(containerName, SR.CONTAINER);
		}
	}

public static void validateContainerName ( String containerName ) { if ( ! ( "$root" . equals ( containerName ) || "$logs" . equals ( containerName ) ) ) { NameValidator . validateShareContainerQueueHelper ( containerName , SR . CONTAINER ) ; } }

Checks if a container name is valid.

@param containerName
A String representing the container name to validate.


public static void validateBlobName(String blobName) {
		if (Utility.isNullOrEmptyOrWhitespace(blobName)) {
			throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.RESOURCE_NAME_EMPTY, SR.BLOB));
		}

		if (blobName.length() < NameValidator.BLOB_FILE_DIRECTORY_MIN_LENGTH || blobName.length() > NameValidator.BLOB_MAX_LENGTH) {
			throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME_LENGTH, SR.BLOB, NameValidator.BLOB_FILE_DIRECTORY_MIN_LENGTH, NameValidator.BLOB_MAX_LENGTH));
		}

		int slashCount =  0;
		for (int i = 0; i < blobName.length(); i++)
		{
			if (blobName.charAt(i) == '/')
			{
				slashCount++;
			}
		}

		if (slashCount >= 254)
		{
			throw new IllegalArgumentException(SR.TOO_MANY_PATH_SEGMENTS);
		}
	}

public static void validateBlobName ( String blobName ) { if ( Utility . isNullOrEmptyOrWhitespace ( blobName ) ) { throw new IllegalArgumentException ( String . format ( Utility . LOCALE_US , SR . RESOURCE_NAME_EMPTY , SR . BLOB ) ) ; } if ( blobName . length ( ) < NameValidator . BLOB_FILE_DIRECTORY_MIN_LENGTH || blobName . length ( ) > NameValidator . BLOB_MAX_LENGTH ) { throw new IllegalArgumentException ( String . format ( Utility . LOCALE_US , SR . INVALID_RESOURCE_NAME_LENGTH , SR . BLOB , NameValidator . BLOB_FILE_DIRECTORY_MIN_LENGTH , NameValidator . BLOB_MAX_LENGTH ) ) ; } int slashCount = 0 ; for ( int i = 0 ; i < blobName . length ( ) ; i ++ ) { if ( blobName . charAt ( i ) == ' ' ) { slashCount ++ ; } } if ( slashCount >= 254 ) { throw new IllegalArgumentException ( SR . TOO_MANY_PATH_SEGMENTS ) ; } }

Checks if a blob name is valid.

@param blobName
A String representing the blob name to validate.


public static void validateFileName(String fileName) {
		NameValidator.ValidateFileDirectoryHelper(fileName, SR.FILE);

		if (fileName.endsWith("/")) {
			throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME, SR.FILE));
		}

		for (String s : NameValidator.RESERVED_FILE_NAMES) {
			if (s.equalsIgnoreCase(fileName)) {
				throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_RESERVED_NAME, SR.FILE));
			}
		}
	}

public static void validateFileName ( String fileName ) { NameValidator . ValidateFileDirectoryHelper ( fileName , SR . FILE ) ; if ( fileName . endsWith ( "/" ) ) { throw new IllegalArgumentException ( String . format ( Utility . LOCALE_US , SR . INVALID_RESOURCE_NAME , SR . FILE ) ) ; } for ( String s : NameValidator . RESERVED_FILE_NAMES ) { if ( s . equalsIgnoreCase ( fileName ) ) { throw new IllegalArgumentException ( String . format ( Utility . LOCALE_US , SR . INVALID_RESOURCE_RESERVED_NAME , SR . FILE ) ) ; } } }

Checks if a file name is valid.

@param fileName
A String representing the file name to validate.


public static void validateTableName(String tableName) {
		if (Utility.isNullOrEmptyOrWhitespace(tableName)) {
			throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.RESOURCE_NAME_EMPTY, SR.TABLE));
		}

		if (tableName.length() < NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MIN_LENGTH || tableName.length() > NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MAX_LENGTH) {
			throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME_LENGTH, SR.TABLE, NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MIN_LENGTH, NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MAX_LENGTH));
		}

		if (!(NameValidator.TABLE_REGEX.matcher(tableName).matches()
				|| NameValidator.METRICS_TABLE_REGEX.matcher(tableName).matches()
				|| tableName.equalsIgnoreCase("$MetricsCapacityBlob"))) {
			throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME, SR.TABLE));
		}
	}

public static void validateTableName ( String tableName ) { if ( Utility . isNullOrEmptyOrWhitespace ( tableName ) ) { throw new IllegalArgumentException ( String . format ( Utility . LOCALE_US , SR . RESOURCE_NAME_EMPTY , SR . TABLE ) ) ; } if ( tableName . length ( ) < NameValidator . CONTAINER_SHARE_QUEUE_TABLE_MIN_LENGTH || tableName . length ( ) > NameValidator . CONTAINER_SHARE_QUEUE_TABLE_MAX_LENGTH ) { throw new IllegalArgumentException ( String . format ( Utility . LOCALE_US , SR . INVALID_RESOURCE_NAME_LENGTH , SR . TABLE , NameValidator . CONTAINER_SHARE_QUEUE_TABLE_MIN_LENGTH , NameValidator . CONTAINER_SHARE_QUEUE_TABLE_MAX_LENGTH ) ) ; } if ( ! ( NameValidator . TABLE_REGEX . matcher ( tableName ) . matches ( ) || NameValidator . METRICS_TABLE_REGEX . matcher ( tableName ) . matches ( ) || tableName . equalsIgnoreCase ( "$MetricsCapacityBlob" ) ) ) { throw new IllegalArgumentException ( String . format ( Utility . LOCALE_US , SR . INVALID_RESOURCE_NAME , SR . TABLE ) ) ; } }

Checks if a table name is valid.

@param tableName
A String representing the table name to validate.


@DoesServiceRequest
    public Iterable<CloudFileShare> listShares(final String prefix) {
        return this.listSharesWithPrefix(prefix, EnumSet.noneOf(ShareListingDetails.class), null /* options */, null /* opContext */);
    }

@
DoesServiceRequest
public
Iterable
<
CloudFileShare
>
listShares
(
final
String
prefix
)
{
return
this
.
listSharesWithPrefix
(
prefix
,
EnumSet
.
noneOf
(
ShareListingDetails
.
class
)
,
/* options */
,
/* opContext */
)
;
}

Returns an enumerable collection of shares whose names begin with the specified prefix for this File service
client.

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

@return An enumerable collection of {@link CloudFileShare} objects retrieved lazily that represent the
shares for this client whose names begin with the specified prefix.

Returns an enumerable collection of shares whose names begin with the specified prefix for this File service client .


@DoesServiceRequest
    public Iterable<CloudFileShare> listShares(final String prefix, final EnumSet<ShareListingDetails> detailsIncluded,
            final FileRequestOptions options, final OperationContext opContext) {
        return this.listSharesWithPrefix(prefix, detailsIncluded, options, opContext);
    }

@ DoesServiceRequest public Iterable < CloudFileShare > listShares ( final String prefix , final EnumSet < ShareListingDetails > detailsIncluded , final FileRequestOptions options , final OperationContext opContext ) { return this . listSharesWithPrefix ( prefix , detailsIncluded , options , opContext ) ; }

Returns an enumerable collection of shares whose names begin with the specified prefix for this File
service client, using the specified details settings, request options, and operation context.

@param prefix
A String that represents the share name prefix.
@param detailsIncluded
A java.util.EnumSet object that contains {@link ShareListingDetails} values that indicate
whether share snapshots and/or metadata will be returned.
@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 An enumerable collection of {@link CloudFileShare} objects retrieved lazily that represents the
shares for this client.

Returns an enumerable collection of shares whose names begin with the specified prefix for this File service client using the specified details settings request options and operation context .


@DoesServiceRequest
    public ResultSegment<CloudFileShare> listSharesSegmented() throws StorageException {
        return this.listSharesSegmented(null, EnumSet.noneOf(ShareListingDetails.class), null, null /* continuationToken */,
                null /* options */, null /* opContext */);
    }

@
DoesServiceRequest
public
ResultSegment
<
CloudFileShare
>
listSharesSegmented
(
)
throws
StorageException
{
return
this
.
listSharesSegmented
(
,
EnumSet
.
noneOf
(
ShareListingDetails
.
class
)
,
,
/* continuationToken */
,
/* options */
,
/* opContext */
)
;
}

Returns a result segment of an enumerable collection of shares for this File service client.

@return A {@link ResultSegment} object that contains a segment of the enumerable collection of
{@link CloudFileShare} objects that represent the shares for this client.

@throws StorageException
If a storage service error occurred.

Returns a result segment of an enumerable collection of shares for this File service client .


@DoesServiceRequest
    public ResultSegment<CloudFileShare> listSharesSegmented(final String prefix) throws StorageException {
        return this.listSharesWithPrefixSegmented(prefix, EnumSet.noneOf(ShareListingDetails.class), null, null /* continuationToken */,
                null /* options */, null /* opContext */);
    }

@
DoesServiceRequest
public
ResultSegment
<
CloudFileShare
>
listSharesSegmented
(
final
String
prefix
)
throws
StorageException
{
return
this
.
listSharesWithPrefixSegmented
(
prefix
,
EnumSet
.
noneOf
(
ShareListingDetails
.
class
)
,
,
/* continuationToken */
,
/* options */
,
/* opContext */
)
;
}

Returns a result segment of an enumerable collection of shares whose names begin with the specified
prefix for this File service client.

@param prefix
A String that represents the prefix of the share name.

@return A {@link ResultSegment} object that contains a segment of the enumerable collection of
{@link CloudFileShare} objects that represent the shares whose names begin with the specified
prefix.

@throws StorageException
If a storage service error occurred.

Returns a result segment of an enumerable collection of shares whose names begin with the specified prefix for this File service client .


private Iterable<CloudFileShare> listSharesWithPrefix(final String prefix,
            final EnumSet<ShareListingDetails> detailsIncluded, FileRequestOptions options, OperationContext opContext) {
        if (opContext == null) {
            opContext = new OperationContext();
        }

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

        SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest();

        return new LazySegmentedIterable<CloudFileClient, Void, CloudFileShare>(this.listSharesWithPrefixSegmentedImpl(
                prefix, detailsIncluded, null, options, segmentedRequest), this, null, options.getRetryPolicyFactory(),
                opContext);
    }

private Iterable < CloudFileShare > listSharesWithPrefix ( final String prefix , final EnumSet < ShareListingDetails > detailsIncluded , FileRequestOptions options , OperationContext opContext ) { if ( opContext == null ) { opContext = new OperationContext ( ) ; } opContext . initialize ( ) ; options = FileRequestOptions . populateAndApplyDefaults ( options , this ) ; SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest ( ) ; return new LazySegmentedIterable < CloudFileClient , Void , CloudFileShare > ( this . listSharesWithPrefixSegmentedImpl ( prefix , detailsIncluded , null , options , segmentedRequest ) , this , null , options . getRetryPolicyFactory ( ) , opContext ) ; }

Returns an enumerable collection of shares whose names begin with the specified prefix, using the
specified details settings, request options, and operation context.

@param prefix
A String that represents the prefix of the share name.
@param detailsIncluded
A java.util.EnumSet object that contains {@link ShareListingDetails} values that indicate
whether share snapshots and/or metadata will be returned.
@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 An enumerable collection of {@link CloudFileShare} objects retrieved lazily that represent the
shares whose names begin with the specified prefix.

Returns an enumerable collection of shares whose names begin with the specified prefix using the specified details settings request options and operation context .


public static void setReflectedEntityCacheDisabled(boolean disableReflectedEntityCache) {
        if (TableServiceEntity.reflectedEntityCache != null && disableReflectedEntityCache) {
            TableServiceEntity.reflectedEntityCache.clear();
        }

        TableServiceEntity.disableReflectedEntityCache = disableReflectedEntityCache;
    }

public static void setReflectedEntityCacheDisabled ( boolean disableReflectedEntityCache ) { if ( TableServiceEntity . reflectedEntityCache != null && disableReflectedEntityCache ) { TableServiceEntity . reflectedEntityCache . clear ( ) ; } TableServiceEntity . disableReflectedEntityCache = disableReflectedEntityCache ; }

Sets a boolean representing whether or not the reflected entity cache is disabled. For most scenarios, disabling
the reflected entity cache is not recommended due to its effect on performance.

The reflected entity cache stores known entity types and their respective reflected entity dictionaries. Rather
than using reflection on a known entity type, the values from the dictionary are used instead.

@param disableReflectedEntityCache
true to disable the reflected entity cache; otherwise, false.

Sets a boolean representing whether or not the reflected entity cache is disabled . For most scenarios disabling the reflected entity cache is not recommended due to its effect on performance .


public static String getDate(final HttpURLConnection request) {
        final String retString = request.getHeaderField("Date");
        return retString == null ? request.getHeaderField(Constants.HeaderConstants.DATE) : retString;
    }

public static String getDate ( final HttpURLConnection request ) { final String retString = request . getHeaderField ( "Date" ) ; return retString == null ? request . getHeaderField ( Constants . HeaderConstants . DATE ) : retString ; }

Gets the Date

@param request
The response from server.
@return The Date.


public static HashMap<String, String> getMetadata(final HttpURLConnection request) {
        return getValuesByHeaderPrefix(request, Constants.HeaderConstants.PREFIX_FOR_STORAGE_METADATA);
    }

public static HashMap < String , String > getMetadata ( final HttpURLConnection request ) { return getValuesByHeaderPrefix ( request , Constants . HeaderConstants . PREFIX_FOR_STORAGE_METADATA ) ; }

Gets the metadata from the request The response from server.

@return the metadata from the request

Gets the metadata from the request The response from server .


public static boolean isServerRequestEncrypted(HttpURLConnection request) {
        return Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_REQUEST_ENCRYPTED));
    }

public static boolean isServerRequestEncrypted ( HttpURLConnection request ) { return Constants . TRUE . equals ( request . getHeaderField ( Constants . HeaderConstants . SERVER_REQUEST_ENCRYPTED ) ) ; }

Gets if the request was encrypted by the server.
@param request
The response from the server.
@return A boolean indicating if the request was encrypted by the server.

Gets if the request was encrypted by the server .


public static StorageExtendedErrorInformation getExtendedErrorInformation(final Reader reader,
            final TablePayloadFormat format) throws JsonParseException, IOException {

        JsonFactory jsonFactory = new JsonFactory();
        JsonParser parser = jsonFactory.createParser(reader);
        try {
            final StorageExtendedErrorInformation errorInfo = new StorageExtendedErrorInformation();

            if (!parser.hasCurrentToken()) {
                parser.nextToken();
            }

            JsonUtilities.assertIsStartObjectJsonToken(parser);

            parser.nextToken();
            JsonUtilities.assertIsFieldNameJsonToken(parser);
            JsonUtilities.assertIsExpectedFieldName(parser, "odata.error");

            // start getting extended error information
            parser.nextToken();
            JsonUtilities.assertIsStartObjectJsonToken(parser);

            // get code
            parser.nextValue();
            JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_CODE);
            errorInfo.setErrorCode(parser.getValueAsString());

            // get message
            parser.nextToken();
            JsonUtilities.assertIsFieldNameJsonToken(parser);
            JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_MESSAGE);

            parser.nextToken();
            JsonUtilities.assertIsStartObjectJsonToken(parser);

            parser.nextValue();
            JsonUtilities.assertIsExpectedFieldName(parser, "lang");

            parser.nextValue();
            JsonUtilities.assertIsExpectedFieldName(parser, "value");
            errorInfo.setErrorMessage(parser.getValueAsString());

            parser.nextToken();
            JsonUtilities.assertIsEndObjectJsonToken(parser);

            parser.nextToken();

            // get innererror if it exists
            if (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
                JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.INNER_ERROR);
                errorInfo.getAdditionalDetails().putAll(parseJsonErrorException(parser));
                parser.nextToken();
            }

            // end code object
            JsonUtilities.assertIsEndObjectJsonToken(parser);

            // end odata.error object
            parser.nextToken();
            JsonUtilities.assertIsEndObjectJsonToken(parser);

            return errorInfo;
        }
        finally {
            parser.close();
        }
    }

Gets the Extended Error information.

@return the Extended Error information.

@param reader
the input stream to read error details from.
@param format
The {@link TablePayloadFormat} to use for parsing
@throws IOException
if an error occurs while accessing the stream with Json.


public static StorageExtendedErrorInformation parseErrorDetails(StorageRequest<CloudTableClient, ?, ?> request) {
        try {
            if (request == null || request.getConnection().getErrorStream() == null) {
                return null;
            }

            return getExtendedErrorInformation(new InputStreamReader(
            		request.getConnection().getErrorStream()),
            		TablePayloadFormat.Json);
        } catch (Exception e) {
            return null;
        }
    }

public static StorageExtendedErrorInformation parseErrorDetails ( StorageRequest < CloudTableClient , ? , ? > request ) { try { if ( request == null || request . getConnection ( ) . getErrorStream ( ) == null ) { return null ; } return getExtendedErrorInformation ( new InputStreamReader ( request . getConnection ( ) . getErrorStream ( ) ) , TablePayloadFormat . Json ) ; } catch ( Exception e ) { return null ; } }

Parse the table extended error information from the response body.

@param request
the request whose body to examine for the error information.
@return The {@link StorageExtendedErrorInformation} parsed from the body or null if parsing fails or the request
contains no body.

Parse the table extended error information from the response body .


private static HashMap<String, String[]> parseJsonErrorException(JsonParser parser) throws JsonParseException,
            IOException {
        HashMap<String, String[]> additionalDetails = new HashMap<String, String[]>();

        parser.nextToken();
        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextToken();
        JsonUtilities.assertIsFieldNameJsonToken(parser);

        while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
            if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_MESSAGE)) {
                parser.nextToken();
                additionalDetails.put(TableConstants.ErrorConstants.ERROR_MESSAGE,
                        new String[] { parser.getValueAsString() });
            }
            else if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_EXCEPTION_TYPE)) {
                parser.nextToken();
                additionalDetails.put(TableConstants.ErrorConstants.ERROR_EXCEPTION_TYPE,
                        new String[] { parser.getValueAsString() });
            }
            else if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_EXCEPTION_STACK_TRACE)) {
                parser.nextToken();
                additionalDetails
                        .put(Constants.ERROR_EXCEPTION_STACK_TRACE, new String[] { parser.getValueAsString() });
            }
            parser.nextToken();
        }

        return additionalDetails;
    }

private static HashMap < String , String [ ] > parseJsonErrorException ( JsonParser parser ) throws JsonParseException , IOException { HashMap < String , String [ ] > additionalDetails = new HashMap < String , String [ ] > ( ) ; parser . nextToken ( ) ; JsonUtilities . assertIsStartObjectJsonToken ( parser ) ; parser . nextToken ( ) ; JsonUtilities . assertIsFieldNameJsonToken ( parser ) ; while ( parser . getCurrentToken ( ) != JsonToken . END_OBJECT ) { if ( parser . getCurrentName ( ) . equals ( TableConstants . ErrorConstants . ERROR_MESSAGE ) ) { parser . nextToken ( ) ; additionalDetails . put ( TableConstants . ErrorConstants . ERROR_MESSAGE , new String [ ] { parser . getValueAsString ( ) } ) ; } else if ( parser . getCurrentName ( ) . equals ( TableConstants . ErrorConstants . ERROR_EXCEPTION_TYPE ) ) { parser . nextToken ( ) ; additionalDetails . put ( TableConstants . ErrorConstants . ERROR_EXCEPTION_TYPE , new String [ ] { parser . getValueAsString ( ) } ) ; } else if ( parser . getCurrentName ( ) . equals ( TableConstants . ErrorConstants . ERROR_EXCEPTION_STACK_TRACE ) ) { parser . nextToken ( ) ; additionalDetails . put ( Constants . ERROR_EXCEPTION_STACK_TRACE , new String [ ] { parser . getValueAsString ( ) } ) ; } parser . nextToken ( ) ; } return additionalDetails ; }

Parses the error exception details from the Json-formatted response.

@param parser
the {@link JsonParser} to use for parsing
@throws IOException
if an error occurs while accessing the stream with Json.
@throws JsonParseException
if an error occurs while parsing the stream.

Parses the error exception details from the Json - formatted response .


public static <T extends SharedAccessPolicy> HashMap<String, T> getAccessIdentifiers(final InputStream stream,
            final Class<T> cls) throws ParserConfigurationException, SAXException, IOException {
        SAXParser saxParser = Utility.getSAXParser();
        SharedAccessPolicyHandler<T> handler = new SharedAccessPolicyHandler<T>(cls);
        saxParser.parse(stream, handler);

        return handler.policies;
    }

public static < T extends SharedAccessPolicy > HashMap < String , T > getAccessIdentifiers ( final InputStream stream , final Class < T > cls ) throws ParserConfigurationException , SAXException , IOException { SAXParser saxParser = Utility . getSAXParser ( ) ; SharedAccessPolicyHandler < T > handler = new SharedAccessPolicyHandler < T > ( cls ) ; saxParser . parse ( stream , handler ) ; return handler . policies ; }

RESERVED FOR INTERNAL USE. Gets the HashMap of SharedAccessPolicies from the response.

@param stream
the stream to read from
@param cls
the SharedAccessPolicy class type
@return the HashMap of SharedAccessPolicies from the response
@throws SAXException
@throws ParserConfigurationException
@throws ParseException
if a date is incorrectly encoded in the stream
@throws IOException

RESERVED FOR INTERNAL USE . Gets the HashMap of SharedAccessPolicies from the response .


public static CopyState getCopyState(final HttpURLConnection request) throws URISyntaxException, ParseException {
        String copyStatusString = request.getHeaderField(Constants.HeaderConstants.COPY_STATUS);
        if (!Utility.isNullOrEmpty(copyStatusString)) {
            final CopyState copyState = new CopyState();

            copyState.setStatus(CopyStatus.parse(copyStatusString));
            copyState.setCopyId(request.getHeaderField(Constants.HeaderConstants.COPY_ID));
            copyState.setStatusDescription(request.getHeaderField(Constants.HeaderConstants.COPY_STATUS_DESCRIPTION));

            final String copyProgressString = request.getHeaderField(Constants.HeaderConstants.COPY_PROGRESS);
            if (!Utility.isNullOrEmpty(copyProgressString)) {
                String[] progressSequence = copyProgressString.split("/");
                copyState.setBytesCopied(Long.parseLong(progressSequence[0]));
                copyState.setTotalBytes(Long.parseLong(progressSequence[1]));
            }

            final String copySourceString = request.getHeaderField(Constants.HeaderConstants.COPY_SOURCE);
            if (!Utility.isNullOrEmpty(copySourceString)) {
                copyState.setSource(new URI(copySourceString));
            }

            final String copyCompletionTimeString =
                    request.getHeaderField(Constants.HeaderConstants.COPY_COMPLETION_TIME);
            if (!Utility.isNullOrEmpty(copyCompletionTimeString)) {
                copyState.setCompletionTime(Utility.parseRFC1123DateFromStringInGMT(copyCompletionTimeString));
            }

            return copyState;
        }
        else {
            return null;
        }
    }

public static CopyState getCopyState ( final HttpURLConnection request ) throws URISyntaxException , ParseException { String copyStatusString = request . getHeaderField ( Constants . HeaderConstants . COPY_STATUS ) ; if ( ! Utility . isNullOrEmpty ( copyStatusString ) ) { final CopyState copyState = new CopyState ( ) ; copyState . setStatus ( CopyStatus . parse ( copyStatusString ) ) ; copyState . setCopyId ( request . getHeaderField ( Constants . HeaderConstants . COPY_ID ) ) ; copyState . setStatusDescription ( request . getHeaderField ( Constants . HeaderConstants . COPY_STATUS_DESCRIPTION ) ) ; final String copyProgressString = request . getHeaderField ( Constants . HeaderConstants . COPY_PROGRESS ) ; if ( ! Utility . isNullOrEmpty ( copyProgressString ) ) { String [ ] progressSequence = copyProgressString . split ( "/" ) ; copyState . setBytesCopied ( Long . parseLong ( progressSequence [ 0 ] ) ) ; copyState . setTotalBytes ( Long . parseLong ( progressSequence [ 1 ] ) ) ; } final String copySourceString = request . getHeaderField ( Constants . HeaderConstants . COPY_SOURCE ) ; if ( ! Utility . isNullOrEmpty ( copySourceString ) ) { copyState . setSource ( new URI ( copySourceString ) ) ; } final String copyCompletionTimeString = request . getHeaderField ( Constants . HeaderConstants . COPY_COMPLETION_TIME ) ; if ( ! Utility . isNullOrEmpty ( copyCompletionTimeString ) ) { copyState . setCompletionTime ( Utility . parseRFC1123DateFromStringInGMT ( copyCompletionTimeString ) ) ; } return copyState ; } else { return null ; } }

Gets the copyState

@param request
The response from server.
@return The CopyState.
@throws URISyntaxException
@throws ParseException


public static FileShareAttributes getFileShareAttributes(final HttpURLConnection request,
            final boolean usePathStyleUris) throws StorageException {
        final FileShareAttributes shareAttributes = new FileShareAttributes();
        final FileShareProperties shareProperties = shareAttributes.getProperties();
        shareProperties.setEtag(BaseResponse.getEtag(request));
        shareProperties.setShareQuota(parseShareQuota(request));
        shareProperties.setLastModified(new Date(request.getLastModified()));
        shareAttributes.setMetadata(getMetadata(request));

        return shareAttributes;
    }

public static FileShareAttributes getFileShareAttributes ( final HttpURLConnection request , final boolean usePathStyleUris ) throws StorageException { final FileShareAttributes shareAttributes = new FileShareAttributes ( ) ; final FileShareProperties shareProperties = shareAttributes . getProperties ( ) ; shareProperties . setEtag ( BaseResponse . getEtag ( request ) ) ; shareProperties . setShareQuota ( parseShareQuota ( request ) ) ; shareProperties . setLastModified ( new Date ( request . getLastModified ( ) ) ) ; shareAttributes . setMetadata ( getMetadata ( request ) ) ; return shareAttributes ; }

Gets the FileShareAttributes from the given request.

@param request
the request to get attributes from
@param usePathStyleUris
a value indicating if the account is using pathSytleUris
@return the FileShareAttributes from the given request.
@throws StorageException

Gets the FileShareAttributes from the given request .


public static FileDirectoryAttributes getFileDirectoryAttributes(final HttpURLConnection request,
            final boolean usePathStyleUris) throws StorageException {
        final FileDirectoryAttributes directoryAttributes = new FileDirectoryAttributes();
        URI tempURI;
        try {
            tempURI = PathUtility.stripSingleURIQueryAndFragment(request.getURL().toURI());
        }
        catch (final URISyntaxException e) {
            final StorageException wrappedUnexpectedException = Utility.generateNewUnexpectedStorageException(e);
            throw wrappedUnexpectedException;
        }

        directoryAttributes.setName(PathUtility.getDirectoryNameFromURI(tempURI, usePathStyleUris));

        final FileDirectoryProperties directoryProperties = directoryAttributes.getProperties();
        directoryProperties.setEtag(BaseResponse.getEtag(request));
        directoryProperties.setLastModified(new Date(request.getLastModified()));
        directoryAttributes.setMetadata(getMetadata(request));
        directoryProperties.setServerEncrypted(
                Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_ENCRYPTED)));

        return directoryAttributes;
    }

public static FileDirectoryAttributes getFileDirectoryAttributes ( final HttpURLConnection request , final boolean usePathStyleUris ) throws StorageException { final FileDirectoryAttributes directoryAttributes = new FileDirectoryAttributes ( ) ; URI tempURI ; try { tempURI = PathUtility . stripSingleURIQueryAndFragment ( request . getURL ( ) . toURI ( ) ) ; } catch ( final URISyntaxException e ) { final StorageException wrappedUnexpectedException = Utility . generateNewUnexpectedStorageException ( e ) ; throw wrappedUnexpectedException ; } directoryAttributes . setName ( PathUtility . getDirectoryNameFromURI ( tempURI , usePathStyleUris ) ) ; final FileDirectoryProperties directoryProperties = directoryAttributes . getProperties ( ) ; directoryProperties . setEtag ( BaseResponse . getEtag ( request ) ) ; directoryProperties . setLastModified ( new Date ( request . getLastModified ( ) ) ) ; directoryAttributes . setMetadata ( getMetadata ( request ) ) ; directoryProperties . setServerEncrypted ( Constants . TRUE . equals ( request . getHeaderField ( Constants . HeaderConstants . SERVER_ENCRYPTED ) ) ) ; return directoryAttributes ; }

Gets the FileDirectoryAttributes from the given request.

@param request
the request to get attributes from.
@param usePathStyleUris
a value indicating if the account is using pathSytleUris.
@return the FileDirectoryAttributes from the given request.
@throws StorageException

Gets the FileDirectoryAttributes from the given request .


public static FileAttributes getFileAttributes(final HttpURLConnection request, final StorageUri resourceURI)
            throws URISyntaxException, ParseException {
        final FileAttributes fileAttributes = new FileAttributes();
        final FileProperties properties = fileAttributes.getProperties();

        properties.setCacheControl(request.getHeaderField(Constants.HeaderConstants.CACHE_CONTROL));
        properties.setContentDisposition(request.getHeaderField(Constants.HeaderConstants.CONTENT_DISPOSITION));
        properties.setContentEncoding(request.getHeaderField(Constants.HeaderConstants.CONTENT_ENCODING));
        properties.setContentLanguage(request.getHeaderField(Constants.HeaderConstants.CONTENT_LANGUAGE));

        // For range gets, only look at 'x-ms-content-md5' for overall MD5
        if (!Utility.isNullOrEmpty(request.getHeaderField(Constants.HeaderConstants.CONTENT_RANGE))) {
            properties.setContentMD5(request.getHeaderField(FileConstants.FILE_CONTENT_MD5_HEADER));
        }
        else {
            properties.setContentMD5(request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5));
        }

        properties.setContentType(request.getHeaderField(Constants.HeaderConstants.CONTENT_TYPE));
        properties.setEtag(BaseResponse.getEtag(request));
        properties.setCopyState(FileResponse.getCopyState(request));
        properties.setServerEncrypted(
                Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_ENCRYPTED)));

        final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US);
        lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE);
        lastModifiedCalendar.setTime(new Date(request.getLastModified()));
        properties.setLastModified(lastModifiedCalendar.getTime());

        final String rangeHeader = request.getHeaderField(Constants.HeaderConstants.CONTENT_RANGE);
        final String xContentLengthHeader = request.getHeaderField(FileConstants.CONTENT_LENGTH_HEADER);

        if (!Utility.isNullOrEmpty(rangeHeader)) {
            properties.setLength(Long.parseLong(rangeHeader.split("/")[1]));
        }
        else if (!Utility.isNullOrEmpty(xContentLengthHeader)) {
            properties.setLength(Long.parseLong(xContentLengthHeader));
        }
        else {
            // using this instead of the request property since the request
            // property only returns an int.
            final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH);

            if (!Utility.isNullOrEmpty(contentLength)) {
                properties.setLength(Long.parseLong(contentLength));
            }
        }

        fileAttributes.setStorageUri(resourceURI);

        fileAttributes.setMetadata(BaseResponse.getMetadata(request));

        return fileAttributes;
    }

Gets the CloudFileAttributes from the given request

@param request
The response from server.
@param resourceURI
The file uri to set.
@return the CloudFileAttributes from the given request
@throws ParseException
@throws URISyntaxException


static String getHttpVerbForOperation(final TableOperationType operationType) {
        if (operationType == TableOperationType.INSERT) {
            return "POST";
        }
        else if (operationType == TableOperationType.DELETE) {
            return "DELETE";
        }
        else if (operationType == TableOperationType.MERGE || operationType == TableOperationType.INSERT_OR_MERGE) {
            return "MERGE";
        }
        else if (operationType == TableOperationType.REPLACE || operationType == TableOperationType.INSERT_OR_REPLACE) {
            return "PUT";
        }
        else if (operationType == TableOperationType.RETRIEVE) {
            return "GET";
        }
        else {
            throw new IllegalArgumentException(SR.UNKNOWN_TABLE_OPERATION);
        }
    }

static String getHttpVerbForOperation ( final TableOperationType operationType ) { if ( operationType == TableOperationType . INSERT ) { return "POST" ; } else if ( operationType == TableOperationType . DELETE ) { return "DELETE" ; } else if ( operationType == TableOperationType . MERGE || operationType == TableOperationType . INSERT_OR_MERGE ) { return "MERGE" ; } else if ( operationType == TableOperationType . REPLACE || operationType == TableOperationType . INSERT_OR_REPLACE ) { return "PUT" ; } else if ( operationType == TableOperationType . RETRIEVE ) { return "GET" ; } else { throw new IllegalArgumentException ( SR . UNKNOWN_TABLE_OPERATION ) ; } }

Reserved for internal use. Returns the HTTP verb for a table operation.

@param operationType
The {@link TableOperation} instance to get the HTTP verb for.
@return
A String containing the HTTP verb to use with the operation.

Reserved for internal use . Returns the HTTP verb for a table operation .


public void fireEvent(final EVENT_TYPE event) {
        for (final StorageEvent<EVENT_TYPE> listener : this.listeners) {
            listener.eventOccurred(event);
        }
    }

public void fireEvent ( final EVENT_TYPE event ) { for ( final StorageEvent < EVENT_TYPE > listener : this . listeners ) { listener . eventOccurred ( event ) ; } }

Fires the event to all subscribed event listeners.

@param event
An EVENTTYPEobject that represents the event being multi-casted.

Fires the event to all subscribed event listeners .


private static void fireSendingRequestEvent(OperationContext opContext, HttpURLConnection request,
            RequestResult result) {
        if (opContext.getSendingRequestEventHandler().hasListeners()
                || OperationContext.getGlobalSendingRequestEventHandler().hasListeners()) {
            SendingRequestEvent event = new SendingRequestEvent(opContext, request, result);
            opContext.getSendingRequestEventHandler().fireEvent(event);
            OperationContext.getGlobalSendingRequestEventHandler().fireEvent(event);
        }
    }

private static void fireSendingRequestEvent ( OperationContext opContext , HttpURLConnection request , RequestResult result ) { if ( opContext . getSendingRequestEventHandler ( ) . hasListeners ( ) || OperationContext . getGlobalSendingRequestEventHandler ( ) . hasListeners ( ) ) { SendingRequestEvent event = new SendingRequestEvent ( opContext , request , result ) ; opContext . getSendingRequestEventHandler ( ) . fireEvent ( event ) ; OperationContext . getGlobalSendingRequestEventHandler ( ) . fireEvent ( event ) ; } }

Fires events representing that a request will be sent.

Fires events representing that a request will be sent .


private static void fireResponseReceivedEvent(OperationContext opContext, HttpURLConnection request,
            RequestResult result) {
        if (opContext.getResponseReceivedEventHandler().hasListeners()
                || OperationContext.getGlobalResponseReceivedEventHandler().hasListeners()) {
            ResponseReceivedEvent event = new ResponseReceivedEvent(opContext, request, result);
            opContext.getResponseReceivedEventHandler().fireEvent(event);
            OperationContext.getGlobalResponseReceivedEventHandler().fireEvent(event);
        }
    }

private static void fireResponseReceivedEvent ( OperationContext opContext , HttpURLConnection request , RequestResult result ) { if ( opContext . getResponseReceivedEventHandler ( ) . hasListeners ( ) || OperationContext . getGlobalResponseReceivedEventHandler ( ) . hasListeners ( ) ) { ResponseReceivedEvent event = new ResponseReceivedEvent ( opContext , request , result ) ; opContext . getResponseReceivedEventHandler ( ) . fireEvent ( event ) ; OperationContext . getGlobalResponseReceivedEventHandler ( ) . fireEvent ( event ) ; } }

Fires events representing that a response has been received.

Fires events representing that a response has been received .


private static void fireErrorReceivingResponseEvent(OperationContext opContext, HttpURLConnection request,
            RequestResult result) {
        if (opContext.getErrorReceivingResponseEventHandler().hasListeners()
                || OperationContext.getGlobalErrorReceivingResponseEventHandler().hasListeners()) {
            ErrorReceivingResponseEvent event = new ErrorReceivingResponseEvent(opContext, request, result);
            opContext.getErrorReceivingResponseEventHandler().fireEvent(event);
            OperationContext.getGlobalErrorReceivingResponseEventHandler().fireEvent(event);
        }
    }

Fires events representing that an error occurred when receiving the response.

Fires events representing that an error occurred when receiving the response .


private static void fireRequestCompletedEvent(OperationContext opContext, HttpURLConnection request,
            RequestResult result) {
        if (opContext.getRequestCompletedEventHandler().hasListeners()
                || OperationContext.getGlobalRequestCompletedEventHandler().hasListeners()) {
            RequestCompletedEvent event = new RequestCompletedEvent(opContext, request, result);
            opContext.getRequestCompletedEventHandler().fireEvent(event);
            OperationContext.getGlobalRequestCompletedEventHandler().fireEvent(event);
        }
    }

private static void fireRequestCompletedEvent ( OperationContext opContext , HttpURLConnection request , RequestResult result ) { if ( opContext . getRequestCompletedEventHandler ( ) . hasListeners ( ) || OperationContext . getGlobalRequestCompletedEventHandler ( ) . hasListeners ( ) ) { RequestCompletedEvent event = new RequestCompletedEvent ( opContext , request , result ) ; opContext . getRequestCompletedEventHandler ( ) . fireEvent ( event ) ; OperationContext . getGlobalRequestCompletedEventHandler ( ) . fireEvent ( event ) ; } }

Fires events representing that a response received from the service is fully processed.

Fires events representing that a response received from the service is fully processed .


private static void fireRetryingEvent(OperationContext opContext, HttpURLConnection request, RequestResult result,
            RetryContext retryContext) {
        if (opContext.getRetryingEventHandler().hasListeners()
                || OperationContext.getGlobalRetryingEventHandler().hasListeners()) {
            RetryingEvent event = new RetryingEvent(opContext, request, result, retryContext);
            opContext.getRetryingEventHandler().fireEvent(event);
            OperationContext.getGlobalRetryingEventHandler().fireEvent(event);
        }
    }

private static void fireRetryingEvent ( OperationContext opContext , HttpURLConnection request , RequestResult result , RetryContext retryContext ) { if ( opContext . getRetryingEventHandler ( ) . hasListeners ( ) || OperationContext . getGlobalRetryingEventHandler ( ) . hasListeners ( ) ) { RetryingEvent event = new RetryingEvent ( opContext , request , result , retryContext ) ; opContext . getRetryingEventHandler ( ) . fireEvent ( event ) ; OperationContext . getGlobalRetryingEventHandler ( ) . fireEvent ( event ) ; } }

Fires events representing that a request will be retried.

Fires events representing that a request will be retried .


public static void assertContinuationType(final ResultContinuation continuationToken,
            final ResultContinuationType continuationType) {
        if (continuationToken != null) {
            if (!(continuationToken.getContinuationType() == ResultContinuationType.NONE || continuationToken
                    .getContinuationType() == continuationType)) {
                final String errorMessage = String.format(Utility.LOCALE_US, SR.UNEXPECTED_CONTINUATION_TYPE,
                        continuationToken.getContinuationType(), continuationType);
                throw new IllegalArgumentException(errorMessage);
            }
        }
    }

public static void assertContinuationType ( final ResultContinuation continuationToken , final ResultContinuationType continuationType ) { if ( continuationToken != null ) { if ( ! ( continuationToken . getContinuationType ( ) == ResultContinuationType . NONE || continuationToken . getContinuationType ( ) == continuationType ) ) { final String errorMessage = String . format ( Utility . LOCALE_US , SR . UNEXPECTED_CONTINUATION_TYPE , continuationToken . getContinuationType ( ) , continuationType ) ; throw new IllegalArgumentException ( errorMessage ) ; } } }

Asserts a continuation token is of the specified type.

@param continuationToken
A {@link ResultContinuation} object that represents the continuation token whose type is being
examined.
@param continuationType
A {@link ResultContinuationType} value that represents the continuation token type being asserted with
the specified continuation token.

Asserts a continuation token is of the specified type .


public static void assertInBounds(final String param, final long value, final long min, final long max) {
        if (value < min || value > max) {
            throw new IllegalArgumentException(String.format(SR.PARAMETER_NOT_IN_RANGE, param, min, max));
        }
    }

public static void assertInBounds ( final String param , final long value , final long min , final long max ) { if ( value < min || value > max ) { throw new IllegalArgumentException ( String . format ( SR . PARAMETER_NOT_IN_RANGE , param , min , max ) ) ; } }

Asserts that the specified integer is in the valid range.

@param param
A String that represents the name of the parameter, which becomes the exception message
text if the value parameter is out of bounds.
@param value
The value of the specified parameter.
@param min
The minimum value for the specified parameter.
@param max
The maximum value for the specified parameter.

Asserts that the specified integer is in the valid range .


public static void assertGreaterThanOrEqual(final String param, final long value, final long min) {
        if (value < min) {
            throw new IllegalArgumentException(String.format(SR.PARAMETER_SHOULD_BE_GREATER_OR_EQUAL, param, min));
        }
    }

public static void assertGreaterThanOrEqual ( final String param , final long value , final long min ) { if ( value < min ) { throw new IllegalArgumentException ( String . format ( SR . PARAMETER_SHOULD_BE_GREATER_OR_EQUAL , param , min ) ) ; } }

Asserts that the specified value is greater than or equal to the min value.

@param param
A String that represents the name of the parameter, which becomes the exception message
text if the value parameter is out of bounds.
@param value
The value of the specified parameter.
@param min
The minimum value for the specified parameter.

Asserts that the specified value is greater than or equal to the min value .


public static boolean validateMaxExecutionTimeout(Long operationExpiryTimeInMs, long additionalInterval) {
        if (operationExpiryTimeInMs != null) {
            long currentTime = new Date().getTime();
            return operationExpiryTimeInMs < currentTime + additionalInterval;
        }
        return false;
    }

public static boolean validateMaxExecutionTimeout ( Long operationExpiryTimeInMs , long additionalInterval ) { if ( operationExpiryTimeInMs != null ) { long currentTime = new Date ( ) . getTime ( ) ; return operationExpiryTimeInMs < currentTime + additionalInterval ; } return false ; }

Returns a value representing whether the maximum execution time would be surpassed.

@param operationExpiryTimeInMs
the time the request expires
@param additionalInterval
any additional time required from now
@return true if the maximum execution time would be surpassed; otherwise, false.

Returns a value representing whether the maximum execution time would be surpassed .


public static int getRemainingTimeout(Long operationExpiryTimeInMs, Integer timeoutIntervalInMs) throws StorageException {
        if (operationExpiryTimeInMs != null) {
            long remainingTime = operationExpiryTimeInMs - new Date().getTime();
            if (remainingTime > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            else if (remainingTime > 0) {
                return (int) remainingTime;
            }
            else {
                TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);
                StorageException translatedException = new StorageException(
                        StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION,
                        Constants.HeaderConstants.HTTP_UNUSED_306, null, timeoutException);
                throw translatedException;
            }
        }
        else if (timeoutIntervalInMs != null) {
            return timeoutIntervalInMs + Constants.DEFAULT_READ_TIMEOUT;
        }
        else {
            return Constants.DEFAULT_READ_TIMEOUT;
        }
    }

public static int getRemainingTimeout ( Long operationExpiryTimeInMs , Integer timeoutIntervalInMs ) throws StorageException { if ( operationExpiryTimeInMs != null ) { long remainingTime = operationExpiryTimeInMs - new Date ( ) . getTime ( ) ; if ( remainingTime > Integer . MAX_VALUE ) { return Integer . MAX_VALUE ; } else if ( remainingTime > 0 ) { return ( int ) remainingTime ; } else { TimeoutException timeoutException = new TimeoutException ( SR . MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION ) ; StorageException translatedException = new StorageException ( StorageErrorCodeStrings . OPERATION_TIMED_OUT , SR . MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION , Constants . HeaderConstants . HTTP_UNUSED_306 , null , timeoutException ) ; throw translatedException ; } } else if ( timeoutIntervalInMs != null ) { return timeoutIntervalInMs + Constants . DEFAULT_READ_TIMEOUT ; } else { return Constants . DEFAULT_READ_TIMEOUT ; } }

Returns a value representing the remaining time before the operation expires.

@param operationExpiryTimeInMs
the time the request expires
@param timeoutIntervalInMs
the server side timeout interval
@return the remaining time before the operation expires
@throws StorageException
wraps a TimeoutException if there is no more time remaining

Returns a value representing the remaining time before the operation expires .


public static boolean determinePathStyleFromUri(final URI baseURI) {
        String path = baseURI.getPath();
        if (path != null && path.startsWith("/")) {
            path = path.substring(1);
        }

        // if the path is null or empty, this is not path-style
        if (Utility.isNullOrEmpty(path)) {
            return false;
        }

        // if this contains a port or has a host which is not DNS, this is path-style
        return pathStylePorts.contains(baseURI.getPort()) || !isHostDnsName(baseURI);
    }

Returns a value that indicates whether a specified URI is a path-style URI.

@param baseURI
A java.net.URI value that represents the URI being checked.
@return true if the specified URI is path-style; otherwise, false.

Returns a value that indicates whether a specified URI is a path - style URI .


private static boolean isHostDnsName(URI uri) {
        String host = uri.getHost();
        for (int i = 0; i < host.length(); i++) {
            char hostChar = host.charAt(i);
            if (!Character.isDigit(hostChar) && !(hostChar == '.')) {
                return true;
            }
        }
        return false;
    }

private static boolean isHostDnsName ( URI uri ) { String host = uri . getHost ( ) ; for ( int i = 0 ; i < host . length ( ) ; i ++ ) { char hostChar = host . charAt ( i ) ; if ( ! Character . isDigit ( hostChar ) && ! ( hostChar == ' ' ) ) { return true ; } } return false ; }

Returns a boolean indicating whether the host of the specified URI is DNS.

@param uri
The URI whose host to evaluate.
@return true if the host is DNS; otherwise, false.

Returns a boolean indicating whether the host of the specified URI is DNS .


public static String formatETag(final String etag) {
        if (etag.startsWith("\"") && etag.endsWith("\"")) {
            return etag;
        }
        else {
            return String.format("\"%s\"", etag);
        }
    }

public static String formatETag ( final String etag ) { if ( etag . startsWith ( "\"" ) && etag . endsWith ( "\"" ) ) { return etag ; } else { return String . format ( "\"%s\"" , etag ) ; } }

Reads character data for the Etag element from an XML stream reader.

@param xmlr
An XMLStreamReader object that represents the source XML stream reader.

@return A String that represents the character data for the Etag element.

Reads character data for the Etag element from an XML stream reader .


public static StorageException generateNewUnexpectedStorageException(final Exception cause) {
        final StorageException exceptionRef = new StorageException(StorageErrorCode.NONE.toString(),
                "Unexpected internal storage client error.", 306, // unused
                null, null);
        exceptionRef.initCause(cause);
        return exceptionRef;
    }

Returns an unexpected storage exception.

@param cause
An Exception object that represents the initial exception that caused the unexpected
error.

@return A {@link StorageException} object that represents the unexpected storage exception being thrown.

Returns an unexpected storage exception .


public static String getStandardHeaderValue(final HttpURLConnection conn, final String headerName) {
        final String headerValue = conn.getRequestProperty(headerName);

        // Coalesce null value
        return headerValue == null ? Constants.EMPTY_STRING : headerValue;
    }

public
static
String
getStandardHeaderValue
(
final
HttpURLConnection
conn
,
final
String
headerName
)
{
final
String
headerValue
=
conn
.
getRequestProperty
(
headerName
)
;
// Coalesce null value
return
headerValue
==
Constants
.
EMPTY_STRING
:
headerValue
;
}

Returns the standard header value from the specified connection request, or an empty string if no header value
has been specified for the request.

@param conn
An HttpURLConnection object that represents the request.
@param headerName
A String that represents the name of the header being requested.

@return A String that represents the header value, or null if there is no corresponding
header value for headerName.

Returns the standard header value from the specified connection request or an empty string if no header value has been specified for the request .


public static Date parseDateFromString(final String value, final String pattern, final TimeZone timeZone)
            throws ParseException {
        final DateFormat rfc1123Format = new SimpleDateFormat(pattern, Utility.LOCALE_US);
        rfc1123Format.setTimeZone(timeZone);
        return rfc1123Format.parse(value);
   }

public static Date parseDateFromString ( final String value , final String pattern , final TimeZone timeZone ) throws ParseException { final DateFormat rfc1123Format = new SimpleDateFormat ( pattern , Utility . LOCALE_US ) ; rfc1123Format . setTimeZone ( timeZone ) ; return rfc1123Format . parse ( value ) ; }

Returns a GMT date in the specified format

@param value
the string to parse
@return the GMT date, as a Date
@throws ParseException
If the specified string is invalid


public static Date parseRFC1123DateFromStringInGMT(final String value) throws ParseException {
        final DateFormat format = new SimpleDateFormat(RFC1123_GMT_PATTERN, Utility.LOCALE_US);
        format.setTimeZone(GMT_ZONE);
        return format.parse(value);
    }

public static Date parseRFC1123DateFromStringInGMT ( final String value ) throws ParseException { final DateFormat format = new SimpleDateFormat ( RFC1123_GMT_PATTERN , Utility . LOCALE_US ) ; format . setTimeZone ( GMT_ZONE ) ; return format . parse ( value ) ; }

Returns a GMT date for the specified string in the RFC1123 pattern.

@param value
A String that represents the string to parse.

@return A Date object that represents the GMT date in the RFC1123 pattern.

@throws ParseException
If the specified string is invalid.

Returns a GMT date for the specified string in the RFC1123 pattern .


public static String safeRelativize(final URI baseURI, final URI toUri) throws URISyntaxException {
        // For compatibility followed
        // http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx

        // if host and scheme are not identical return from uri
        if (!baseURI.getHost().equals(toUri.getHost()) || !baseURI.getScheme().equals(toUri.getScheme())) {
            return toUri.toString();
        }

        final String basePath = baseURI.getPath();
        String toPath = toUri.getPath();

        int truncatePtr = 1;

        // Seek to first Difference
        // int maxLength = Math.min(basePath.length(), toPath.length());
        int m = 0;
        int ellipsesCount = 0;
        for (; m < basePath.length(); m++) {
            if (m >= toPath.length()) {
                if (basePath.charAt(m) == '/') {
                    ellipsesCount++;
                }
            }
            else {
                if (basePath.charAt(m) != toPath.charAt(m)) {
                    break;
                }
                else if (basePath.charAt(m) == '/') {
                    truncatePtr = m + 1;
                }
            }
        }

        // ../containername and ../containername/{path} should increment the truncatePtr
        // otherwise toPath will incorrectly begin with /containername
        if (m < toPath.length() && toPath.charAt(m) == '/') {
            // this is to handle the empty directory case with the '/' delimiter
            // for example, ../containername/ and ../containername// should not increment the truncatePtr
            if (!(toPath.charAt(m - 1) == '/' && basePath.charAt(m - 1) == '/')) {
                truncatePtr = m + 1;
            }
        }

        if (m == toPath.length()) {
            // No path difference, return query + fragment
            return new URI(null, null, null, toUri.getQuery(), toUri.getFragment()).toString();
        }
        else {
            toPath = toPath.substring(truncatePtr);
            final StringBuilder sb = new StringBuilder();
            while (ellipsesCount > 0) {
                sb.append("../");
                ellipsesCount--;
            }

            if (!Utility.isNullOrEmpty(toPath)) {
                sb.append(toPath);
            }

            if (!Utility.isNullOrEmpty(toUri.getQuery())) {
                sb.append("?");
                sb.append(toUri.getQuery());
            }
            if (!Utility.isNullOrEmpty(toUri.getFragment())) {
                sb.append("#");
                sb.append(toUri.getRawFragment());
            }

            return sb.toString();
        }
    }

Determines the relative difference between the two specified URIs.

@param baseURI
A java.net.URI object that represents the base URI for which toUri will be
made relative.
@param toUri
A java.net.URI object that represents the URI to make relative to baseURI.

@return A String that either represents the relative URI of toUri to
baseURI, or the URI of toUri itself, depending on whether the hostname and
scheme are identical for toUri and baseURI. If the hostname and scheme of
baseURI and toUri are identical, this method returns an unencoded relative URI
such that if appended to baseURI, it will yield toUri. If the hostname or
scheme of baseURI and toUri are not identical, this method returns an unencoded
full URI specified by toUri.

@throws URISyntaxException
If baseURI or toUri is invalid.

Determines the relative difference between the two specified URIs .


public static void logHttpError(StorageException ex, OperationContext opContext) {
        if (Logger.shouldLog(opContext, Log.DEBUG)) {
            try {
                StringBuilder bld = new StringBuilder();
                bld.append("Error response received. ");

                bld.append("HttpStatusCode= ");
                bld.append(ex.getHttpStatusCode());

                bld.append(", HttpStatusMessage= ");
                bld.append(ex.getMessage());

                bld.append(", ErrorCode= ");
                bld.append(ex.getErrorCode());

                StorageExtendedErrorInformation extendedError = ex.getExtendedErrorInformation();
                if (extendedError != null) {
                    bld.append(", ExtendedErrorInformation= {ErrorMessage= ");
                    bld.append(extendedError.getErrorMessage());

                    HashMap<String, String[]> details = extendedError.getAdditionalDetails();
                    if (details != null) {
                        bld.append(", AdditionalDetails= { ");
                        for (Entry<String, String[]> detail : details.entrySet()) {
                            bld.append(detail.getKey());
                            bld.append("= ");

                            for (String value : detail.getValue()) {
                                bld.append(value);
                            }
                            bld.append(",");
                        }
                        bld.setCharAt(bld.length() - 1, '}');
                    }
                    bld.append("}");
                }

                Logger.debug(opContext, bld.toString());
            } catch (Exception e) {
                // Do nothing
            }
        }
    }

Serializes the parsed StorageException. If an exception is encountered, returns empty string.

@param ex
The StorageException to serialize.
@param opContext
The operation context which provides the logger.

Serializes the parsed StorageException . If an exception is encountered returns empty string .


public static void logHttpResponse(HttpURLConnection conn, OperationContext opContext) throws IOException {
        if (Logger.shouldLog(opContext, Log.VERBOSE)) {
            try {
                StringBuilder bld = new StringBuilder();

                // This map's null key will contain the response code and message
                for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
                    if (header.getKey() != null) {
                        bld.append(header.getKey());
                        bld.append(": ");
                    }

                    for (int i = 0; i < header.getValue().size(); i++) {
                        bld.append(header.getValue().get(i));
                        if (i < header.getValue().size() - 1) {
                            bld.append(",");
                        }
                    }
                    bld.append('\n');
                }

                Logger.verbose(opContext, bld.toString());
            } catch (Exception e) {
                // Do nothing
            }
        }
    }

Logs the HttpURLConnection response. If an exception is encountered, logs nothing.

@param conn
The HttpURLConnection to serialize.
@param opContext
The operation context which provides the logger.

Logs the HttpURLConnection response . If an exception is encountered logs nothing .


protected static String trimEnd(final String value, final char trimChar) {
        int stopDex = value.length() - 1;
        while (stopDex > 0 && value.charAt(stopDex) == trimChar) {
            stopDex--;
        }

        return stopDex == value.length() - 1 ? value : value.substring(stopDex);
    }

protected static String trimEnd ( final String value , final char trimChar ) { int stopDex = value . length ( ) - 1 ; while ( stopDex > 0 && value . charAt ( stopDex ) == trimChar ) { stopDex -- ; } return stopDex == value . length ( ) - 1 ? value : value . substring ( stopDex ) ; }

Trims the specified character from the end of a string.

@param value
A String that represents the string to trim.
@param trimChar
The character to trim from the end of the string.

@return The string with the specified character trimmed from the end.

Trims the specified character from the end of a string .


public static String trimStart(final String value) {
        int spaceDex = 0;
        while (spaceDex < value.length() && value.charAt(spaceDex) == ' ') {
            spaceDex++;
        }

        return value.substring(spaceDex);
    }

public static String trimStart ( final String value ) { int spaceDex = 0 ; while ( spaceDex < value . length ( ) && value . charAt ( spaceDex ) == ' ' ) { spaceDex ++ ; } return value . substring ( spaceDex ) ; }

Trims whitespace from the beginning of a string.

@param value
A String that represents the string to trim.

@return The string with whitespace trimmed from the beginning.

Trims whitespace from the beginning of a string .


public static Date parseDate(String dateString) {
        String pattern = MAX_PRECISION_PATTERN;
        switch(dateString.length()) {
            case 28: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"-> [2012-01-04T23:21:59.1234567Z] length = 28
            case 27: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"-> [2012-01-04T23:21:59.123456Z] length = 27
            case 26: // "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"-> [2012-01-04T23:21:59.12345Z] length = 26
            case 25: // "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z] length = 25
            case 24: // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z] length = 24
                dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH);
                break;
            case 23: // "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z] length = 23
                // SS is assumed to be milliseconds, so a trailing 0 is necessary
                dateString = dateString.replace("Z", "0");
                break;
            case 22: // "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z] length = 22
                // S is assumed to be milliseconds, so trailing 0's are necessary
                dateString = dateString.replace("Z", "00");
                break;
            case 20: // "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length = 20
                pattern = Utility.ISO8601_PATTERN;
                break;
            case 17: // "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17
                pattern = Utility.ISO8601_PATTERN_NO_SECONDS;
                break;
            default:
                throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString));
        }

        final DateFormat format = new SimpleDateFormat(pattern, Utility.LOCALE_US);
        format.setTimeZone(UTC_ZONE);
        try {
            return format.parse(dateString);
        }
        catch (final ParseException e) {
            throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString), e);
        }
    }

Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it
with up to millisecond precision.

@param dateString
the String to be interpreted as a Date

@return the corresponding Date object

Given a String representing a date in a form of the ISO8601 pattern generates a Date representing it with up to millisecond precision .


public static RequestLocationMode getListingLocationMode(ResultContinuation token) {
        if ((token != null) && token.getTargetLocation() != null) {
            switch (token.getTargetLocation()) {
                case PRIMARY:
                    return RequestLocationMode.PRIMARY_ONLY;

                case SECONDARY:
                    return RequestLocationMode.SECONDARY_ONLY;

                default:
                    throw new IllegalArgumentException(String.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, "token",
                            token.getTargetLocation()));
            }
        }

        return RequestLocationMode.PRIMARY_OR_SECONDARY;
    }

public static RequestLocationMode getListingLocationMode ( ResultContinuation token ) { if ( ( token != null ) && token . getTargetLocation ( ) != null ) { switch ( token . getTargetLocation ( ) ) { case PRIMARY : return RequestLocationMode . PRIMARY_ONLY ; case SECONDARY : return RequestLocationMode . SECONDARY_ONLY ; default : throw new IllegalArgumentException ( String . format ( SR . ARGUMENT_OUT_OF_RANGE_ERROR , "token" , token . getTargetLocation ( ) ) ) ; } } return RequestLocationMode . PRIMARY_OR_SECONDARY ; }

Determines which location can the listing command target by looking at the
continuation token.

@param token
Continuation token
@return
Location mode

Determines which location can the listing command target by looking at the continuation token .


protected static final QueueRequestOptions populateAndApplyDefaults(QueueRequestOptions options, final CloudQueueClient client) {
        QueueRequestOptions modifiedOptions = new QueueRequestOptions(options);
        RequestOptions.populateRequestOptions(modifiedOptions, client.getDefaultRequestOptions(), true /* setStartTime */);
        QueueRequestOptions.applyDefaults(modifiedOptions);
        return modifiedOptions;
    }

protected
static
final
QueueRequestOptions
populateAndApplyDefaults
(
QueueRequestOptions
options
,
final
CloudQueueClient
client
)
{
QueueRequestOptions
modifiedOptions
=
new
QueueRequestOptions
(
options
)
;
RequestOptions
.
populateRequestOptions
(
modifiedOptions
,
client
.
getDefaultRequestOptions
(
)
,
true
/* setStartTime */
)
;
QueueRequestOptions
.
applyDefaults
(
modifiedOptions
)
;
return
modifiedOptions
;
}

Populates the default timeout and retry policy from client if they are not set.

@param options
The input options to copy from when applying defaults
@param client
The {@link CloudQueueClient} service client to populate the
default values from.

Populates the default timeout and retry policy from client if they are not set .


public String readString() throws IOException {
        String temp = this.readField(false /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return temp;
        }
    }

public
String
readString
(
)
throws
IOException
{
String
temp
=
this
.
readField
(
false
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
temp
;
}
}

Read a String from the stream.

@return
the String read.
@throws IOException


public String readQuotedString() throws IOException {
        String temp = this.readField(true /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return temp;
        }
    }

public
String
readQuotedString
(
)
throws
IOException
{
String
temp
=
this
.
readField
(
true
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
temp
;
}
}

Read a quoted String from the stream.

@return
the String read.
@throws IOException


public Boolean readBoolean() throws IOException {
        String temp = this.readField(false /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return Boolean.parseBoolean(temp);
        }
    }

public
Boolean
readBoolean
(
)
throws
IOException
{
String
temp
=
this
.
readField
(
false
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
Boolean
.
parseBoolean
(
temp
)
;
}
}

Read a Boolean from the stream.

@return
the Boolean read.
@throws IOException


public Date readDate(DateFormat format) throws IOException, ParseException {
        String temp = this.readField(false /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return format.parse(temp);
        }
    }

public
Date
readDate
(
DateFormat
format
)
throws
IOException
,
ParseException
{
String
temp
=
this
.
readField
(
false
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
format
.
parse
(
temp
)
;
}
}

Read a Date from the stream.

@param format
the format in which the date is stored, for parsing purposes.
@return
the Date read.
@throws IOException
@throws ParseException


public Double readDouble() throws IOException {
        String temp = this.readField(false /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return Double.parseDouble(temp);
        }
    }

public
Double
readDouble
(
)
throws
IOException
{
String
temp
=
this
.
readField
(
false
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
Double
.
parseDouble
(
temp
)
;
}
}

Read a Double from the stream.

@return
the Double read.
@throws IOException


public UUID readUuid() throws IOException {
        String temp = this.readField(false /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return UUID.fromString(temp);
        }
    }

public
UUID
readUuid
(
)
throws
IOException
{
String
temp
=
this
.
readField
(
false
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
UUID
.
fromString
(
temp
)
;
}
}

Read a UUID from the stream.

@return
the UUID read.
@throws IOException


public Integer readInteger() throws IOException {
        String temp = this.readField(false /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return Integer.parseInt(temp);
        }
    }

public
Integer
readInteger
(
)
throws
IOException
{
String
temp
=
this
.
readField
(
false
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
Integer
.
parseInt
(
temp
)
;
}
}

Read an Integer from the stream.

@return
the Integer read.
@throws IOException


public Long readLong() throws IOException {
        String temp = this.readField(false /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return Long.parseLong(temp);
        }
    }

public
Long
readLong
(
)
throws
IOException
{
String
temp
=
this
.
readField
(
false
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
Long
.
parseLong
(
temp
)
;
}
}

Read a Long from the stream.

@return
the Long read.
@throws IOException


public URI readUri() throws URISyntaxException, IOException {
        String temp = this.readField(true /* isQuotedString */);

        if (Utility.isNullOrEmpty(temp)) {
            return null;
        }
        else {
            return new URI(Html.fromHtml(temp).toString());
        }
    }

public
URI
readUri
(
)
throws
URISyntaxException
,
IOException
{
String
temp
=
this
.
readField
(
true
/* isQuotedString */
)
;
if
(
Utility
.
isNullOrEmpty
(
temp
)
)
{
return
;
}
else
{
return
new
URI
(
Html
.
fromHtml
(
temp
)
.
toString
(
)
)
;
}
}

Read a URI from the stream.

@return
the URI read.
@throws URISyntaxException
@throws IOException


private void readDelimiter(char delimiter) throws IOException {
        if (this.isEndOfFile()) {
            throw new EOFException(SR.LOG_STREAM_END_ERROR);
        }
        else {
            int read = this.read();
            if (read == -1 || (char) read != delimiter) {
                throw new IllegalStateException(SR.LOG_STREAM_DELIMITER_ERROR);
            }
        }
    }

private void readDelimiter ( char delimiter ) throws IOException { if ( this . isEndOfFile ( ) ) { throw new EOFException ( SR . LOG_STREAM_END_ERROR ) ; } else { int read = this . read ( ) ; if ( read == - 1 || ( char ) read != delimiter ) { throw new IllegalStateException ( SR . LOG_STREAM_DELIMITER_ERROR ) ; } } }

Read a delimiter from the stream.

@param delimiter
the delimiter to read.
@throws IOException


private boolean tryPeekDelimiter(char delimiter) throws IOException {
        if (this.isEndOfFile()) {
            throw new EOFException(SR.LOG_STREAM_END_ERROR);
        }
        else {
            if ((char) this.peek() != delimiter) {
                return false;
            }
            else {
                return true;
            }
        }
    }

private boolean tryPeekDelimiter ( char delimiter ) throws IOException { if ( this . isEndOfFile ( ) ) { throw new EOFException ( SR . LOG_STREAM_END_ERROR ) ; } else { if ( ( char ) this . peek ( ) != delimiter ) { return false ; } else { return true ; } } }

Checks to see if the next character is the delimiter expected.

@param delimiter
the delimiter to try to peek.
@return
@throws IOException

Checks to see if the next character is the delimiter expected .


private String readField(boolean isQuotedString) throws IOException {
        if (!this.isFirstFieldInRecord) {
            this.readDelimiter(LogRecordStreamReader.FIELD_DELIMITER);
        }
        else {
            this.isFirstFieldInRecord = false;
        }

        // Read a field, handling field/record delimiters in quotes and not counting them,
        // and also check that there are no record delimiters since they are only expected
        // outside of a field.
        // Note: We only need to handle strings that are quoted once from the beginning,
        // (e.g. "mystring"). We do not need to handle nested quotes or anything because
        // we control the string format.
        StringBuilder fieldBuilder = new StringBuilder();
        boolean hasSeenQuoteForQuotedString = false;
        boolean isExpectingDelimiterForNextCharacterForQuotedString = false;
        while (true) {
            // If EOF when we haven't read the delimiter; unexpected.
            if (this.isEndOfFile()) {
                throw new EOFException(SR.LOG_STREAM_END_ERROR);
            }

            // Since we just checked isEndOfFile above, we know this is a char.
            char c = (char) this.peek();

            // If we hit a delimiter that is not quoted or we hit the delimiter for
            // a quoted string or we hit the empty value string and hit a delimiter,
            // then we have finished reading the field.
            // Note: The empty value string is the only string that we don't require
            // quotes for for a quoted string.
            if ((!isQuotedString || isExpectingDelimiterForNextCharacterForQuotedString || fieldBuilder.length() == 0)
                    && (c == LogRecordStreamReader.FIELD_DELIMITER || c == LogRecordStreamReader.RECORD_DELIMITER)) {
                // The delimiter character was peeked but not read -- they'll be consumed
                // on either the next call to readField or to EndCurrentRecord.
                break;
            }

            if (isExpectingDelimiterForNextCharacterForQuotedString) {
                // We finished reading a quoted string but found no delimiter following it.
                throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR);
            }

            // The character was not a delimiter, so consume and add to builder.
            this.read();
            fieldBuilder.append(c);

            // We need to handle quotes specially since quoted delimiters
            // do not count since they are considered to be part of the
            // quoted string and not actually a delimiter.
            // Note: We use a specific quote character since we control the format
            // and we only allow non-encoded quote characters at the beginning/end
            // of the string.
            if (c == LogRecordStreamReader.QUOTE_CHAR) {
                if (!isQuotedString) {
                    // Non-encoded quote character only allowed for quoted strings.
                    throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR);
                }
                else if (fieldBuilder.length() == 1) {
                    // Opening quote for a quoted string.
                    hasSeenQuoteForQuotedString = true;
                }
                else if (hasSeenQuoteForQuotedString) {
                    // Closing quote for a quoted string.
                    isExpectingDelimiterForNextCharacterForQuotedString = true;
                }
                else {
                    // Unexpected non-encoded quote.
                    throw new IllegalStateException(SR.LOG_STREAM_QUOTE_ERROR);
                }
            }
        }

        String field;

        // Note: For quoted strings we remove the quotes.
        // We do not do this for the empty value string since it represents empty
        // and we don't write that out in quotes even for quoted strings.
        if (isQuotedString && fieldBuilder.length() != 0) {
            field = fieldBuilder.substring(1, fieldBuilder.length() - 1);
        }
        else {
            field = fieldBuilder.toString();
        }

        return field;
    }

Read a field from the stream.

@param isQuotedString
whether the field is encased in quotes and escaped.
@return
the field read.
@throws IOException


@Override
    public RetryPolicy createInstance(final OperationContext opContext) {
        return new RetryExponentialRetry(this.resolvedMinBackoff, this.deltaBackoffIntervalInMs,
                this.resolvedMaxBackoff, this.maximumAttempts);
    }

@ Override public RetryPolicy createInstance ( final OperationContext opContext ) { return new RetryExponentialRetry ( this . resolvedMinBackoff , this . deltaBackoffIntervalInMs , this . resolvedMaxBackoff , this . maximumAttempts ) ; }

Generates a new retry policy for the current request attempt.

@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 RetryPolicy} object that represents the retry policy for the current request attempt.

Generates a new retry policy for the current request attempt .


@Override
    @DoesServiceRequest
    public boolean hasNext() {
        while (this.currentSegment == null
                || (!this.currentSegmentIterator.hasNext() && this.currentSegment != null && this.currentSegment
                        .getHasMoreResults())) {
            try {
                this.currentSegment = ExecutionEngine.executeWithRetry(this.client, this.parentObject,
                        this.segmentGenerator, this.policyFactory, this.opContext);
            }
            catch (final StorageException e) {
                final NoSuchElementException ex = new NoSuchElementException(SR.ENUMERATION_ERROR);
                ex.initCause(e);
                throw ex;
            }
            this.currentSegmentIterator = this.currentSegment.getResults().iterator();

            if (!this.currentSegmentIterator.hasNext() && !this.currentSegment.getHasMoreResults()) {
                return false;
            }
        }

        return this.currentSegmentIterator.hasNext();
    }

@ Override @ DoesServiceRequest public boolean hasNext ( ) { while ( this . currentSegment == null || ( ! this . currentSegmentIterator . hasNext ( ) && this . currentSegment != null && this . currentSegment . getHasMoreResults ( ) ) ) { try { this . currentSegment = ExecutionEngine . executeWithRetry ( this . client , this . parentObject , this . segmentGenerator , this . policyFactory , this . opContext ) ; } catch ( final StorageException e ) { final NoSuchElementException ex = new NoSuchElementException ( SR . ENUMERATION_ERROR ) ; ex . initCause ( e ) ; throw ex ; } this . currentSegmentIterator = this . currentSegment . getResults ( ) . iterator ( ) ; if ( ! this . currentSegmentIterator . hasNext ( ) && ! this . currentSegment . getHasMoreResults ( ) ) { return false ; } } return this . currentSegmentIterator . hasNext ( ) ; }

Indicates if the iterator has another element.

Indicates if the iterator has another element .


protected void setClazzType(final Class<? extends TableEntity> clazzType) {
        Utility.assertNotNull("clazzType", clazzType);
        Utility.checkNullaryCtor(clazzType);
        this.clazzType = clazzType;
    }

protected void setClazzType ( final Class < ? extends TableEntity > clazzType ) { Utility . assertNotNull ( "clazzType" , clazzType ) ; Utility . checkNullaryCtor ( clazzType ) ; this . clazzType = clazzType ; }

Reserved for internal use. Sets the class type of the entity returned by the query.

@param clazzType
The java.lang.Class implementing {@link TableEntity} that represents the entity type for
the query.

Reserved for internal use . Sets the class type of the entity returned by the query .


protected void setResolver(final EntityResolver<?> resolver) {
        Utility.assertNotNull(SR.QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER, resolver);
        this.resolver = resolver;
    }

Reserved for internal use. Sets the resolver to project the entity retrieved as a particular type.

@param resolver
The {@link EntityResolver} instance to use.

Reserved for internal use . Sets the resolver to project the entity retrieved as a particular type .


private static void writeMIMEBoundary(final OutputStreamWriter outWriter, final String boundaryID)
            throws IOException {
        outWriter.write(String.format("--%s\r\n", boundaryID));
    }

private static void writeMIMEBoundary ( final OutputStreamWriter outWriter , final String boundaryID ) throws IOException { outWriter . write ( String . format ( "--%s\r\n" , boundaryID ) ) ; }

Reserved for internal use. Writes a MIME part boundary to the output stream.

@param outWriter
The {@link OutputStreamWriter} to write the MIME part boundary to.
@param boundaryID
The String containing the MIME part boundary string.
@throws IOException
if an error occurs writing to the output stream.

Reserved for internal use . Writes a MIME part boundary to the output stream .


private static void writeMIMEBoundaryClosure(final OutputStreamWriter outWriter, final String boundaryID)
            throws IOException {
        outWriter.write(String.format("--%s--\r\n", boundaryID));
    }

private static void writeMIMEBoundaryClosure ( final OutputStreamWriter outWriter , final String boundaryID ) throws IOException { outWriter . write ( String . format ( "--%s--\r\n" , boundaryID ) ) ; }

Reserved for internal use. Writes a MIME part boundary closure to the output stream.

@param outWriter
The {@link OutputStreamWriter} to write the MIME part boundary closure to.
@param boundaryID
The String containing the MIME part boundary string.
@throws IOException
if an error occurs writing to the output stream.

Reserved for internal use . Writes a MIME part boundary closure to the output stream .


private static void writeMIMEContentType(final OutputStreamWriter outWriter, final String boundaryName)
            throws IOException {
        outWriter.write(String.format("Content-Type: multipart/mixed; boundary=%s\r\n", boundaryName));
    }

Reserved for internal use. Writes a MIME content type string to the output stream.

@param outWriter
The {@link OutputStreamWriter} to write the MIME content type string to.
@param boundaryID
The String containing the MIME part boundary string.
@throws IOException
if an error occurs writing to the output stream.

Reserved for internal use . Writes a MIME content type string to the output stream .


public void add(final String name, final String value) throws StorageException {
        if (Utility.isNullOrEmpty(name)) {
            throw new IllegalArgumentException(SR.QUERY_PARAMETER_NULL_OR_EMPTY);
        }

        this.insertKeyValue(name, value);
    }

public void add ( final String name , final String value ) throws StorageException { if ( Utility . isNullOrEmpty ( name ) ) { throw new IllegalArgumentException ( SR . QUERY_PARAMETER_NULL_OR_EMPTY ) ; } this . insertKeyValue ( name , value ) ; }

Adds a value to the URI with escaping.

@param name
the query key name.
@param value
the query value.
@throws StorageException