All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.microsoft.windowsazure.storage.blob.CloudBlobContainer Maven / Gradle / Ivy

/**
 * Copyright Microsoft Corporation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.microsoft.windowsazure.storage.blob;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.util.Calendar;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;

import javax.xml.stream.XMLStreamException;

import com.microsoft.windowsazure.storage.AccessCondition;
import com.microsoft.windowsazure.storage.Constants;
import com.microsoft.windowsazure.storage.DoesServiceRequest;
import com.microsoft.windowsazure.storage.OperationContext;
import com.microsoft.windowsazure.storage.ResultContinuation;
import com.microsoft.windowsazure.storage.ResultContinuationType;
import com.microsoft.windowsazure.storage.ResultSegment;
import com.microsoft.windowsazure.storage.StorageCredentialsSharedAccessSignature;
import com.microsoft.windowsazure.storage.StorageErrorCodeStrings;
import com.microsoft.windowsazure.storage.StorageException;
import com.microsoft.windowsazure.storage.StorageUri;
import com.microsoft.windowsazure.storage.core.ExecutionEngine;
import com.microsoft.windowsazure.storage.core.LazySegmentedIterable;
import com.microsoft.windowsazure.storage.core.PathUtility;
import com.microsoft.windowsazure.storage.core.RequestLocationMode;
import com.microsoft.windowsazure.storage.core.SR;
import com.microsoft.windowsazure.storage.core.SegmentedStorageRequest;
import com.microsoft.windowsazure.storage.core.SharedAccessSignatureHelper;
import com.microsoft.windowsazure.storage.core.StorageRequest;
import com.microsoft.windowsazure.storage.core.UriQueryBuilder;
import com.microsoft.windowsazure.storage.core.Utility;

/**
 * Represents a container in the Windows Azure Blob service.
 * 

* Containers hold directories, which are encapsulated as {@link CloudBlobDirectory} objects, and directories hold block * blobs and page blobs. Directories can also contain sub-directories. */ public final class CloudBlobContainer { /** * Converts the ACL string to a BlobContainerPermissions object. * * @param aclString * the string to convert. * @return The resulting BlobContainerPermissions object. */ static BlobContainerPermissions getContainerAcl(final String aclString) { BlobContainerPublicAccessType accessType = BlobContainerPublicAccessType.OFF; if (!Utility.isNullOrEmpty(aclString)) { final String lowerAclString = aclString.toLowerCase(); if ("container".equals(lowerAclString)) { accessType = BlobContainerPublicAccessType.CONTAINER; } else if ("blob".equals(lowerAclString)) { accessType = BlobContainerPublicAccessType.BLOB; } else { throw new IllegalArgumentException(String.format(SR.INVALID_ACL_ACCESS_TYPE, aclString)); } } final BlobContainerPermissions retVal = new BlobContainerPermissions(); retVal.setPublicAccess(accessType); return retVal; } /** * Represents the container metadata. */ protected HashMap metadata; /** * Holds the container properties. */ BlobContainerProperties properties; /** * Holds the name of the container. */ String name; /** * Holds the list of URIs for all locations. */ private StorageUri storageUri; /** * Holds a reference to the associated service client. */ private CloudBlobClient blobServiceClient; /** * Initializes a new instance of the CloudBlobContainer class. * * @param client * the reference to the associated service client. */ private CloudBlobContainer(final CloudBlobClient client) { this.metadata = new HashMap(); this.properties = new BlobContainerProperties(); this.blobServiceClient = client; } /** * Creates an instance of the CloudBlobContainer class using the specified address and client. * * @param containerName * A String that represents the container name. * @param client * A {@link CloudBlobClient} object that represents the associated service client, and that specifies the * endpoint for the Blob service. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudBlobContainer(final String containerName, final CloudBlobClient client) throws URISyntaxException, StorageException { this(client); Utility.assertNotNull("client", client); Utility.assertNotNull("containerName", containerName); this.storageUri = PathUtility.appendPathToUri(client.getStorageUri(), containerName); this.name = PathUtility.getContainerNameFromUri(this.storageUri.getPrimaryUri(), client.isUsePathStyleUris()); this.parseQueryAndVerify(this.storageUri, client, client.isUsePathStyleUris()); } /** * Creates an instance of the CloudBlobContainer class using the specified URI and client. * * @param uri * A java.net.URI object that represents the URI of the container. * @param client * A {@link CloudBlobClient} object that represents the associated service client, and that specifies the * endpoint for the Blob service. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudBlobContainer(final URI uri, final CloudBlobClient client) throws URISyntaxException, StorageException { this(new StorageUri(uri), client); } /** * Creates an instance of the CloudBlobContainer class using the specified URI and client. * * @param storageUri * A StorageUri object that represents the URI of the container. * @param client * A {@link CloudBlobClient} object that represents the associated service client, and that specifies the * endpoint for the Blob service. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudBlobContainer(final StorageUri storageUri, final CloudBlobClient client) throws URISyntaxException, StorageException { this(client); Utility.assertNotNull("storageUri", storageUri); this.storageUri = storageUri; boolean usePathStyleUris = client == null ? Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri(), null) : client.isUsePathStyleUris(); this.name = PathUtility.getContainerNameFromUri(storageUri.getPrimaryUri(), usePathStyleUris); this.parseQueryAndVerify(this.storageUri, client, usePathStyleUris); } /** * Creates the container. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void create() throws StorageException { this.create(null /* options */, null /* opContext */); } /** * Creates the container using the specified options and operation context. * * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void create(BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); ExecutionEngine.executeWithRetry(this.blobServiceClient, this, createImpl(options), options.getRetryPolicyFactory(), opContext); } private StorageRequest createImpl(final BlobRequestOptions options) { final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { final HttpURLConnection request = ContainerRequest.create( container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), context); return request; } @Override public void setHeaders(HttpURLConnection connection, CloudBlobContainer container, OperationContext context) { ContainerRequest.addMetadata(connection, container.metadata, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, 0L, null); } @Override public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { this.setNonExceptionedRetryableFailure(true); return null; } // Set attributes final BlobContainerAttributes attributes = ContainerResponse.getAttributes(this.getConnection(), client.isUsePathStyleUris()); container.properties = attributes.getProperties(); container.name = attributes.getName(); return null; } }; return putRequest; } /** * Creates the container if it does not exist. * * @return true if the container did not already exist and was created; otherwise, false. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean createIfNotExists() throws StorageException { return this.createIfNotExists(null /* options */, null /* opContext */); } /** * Creates the container if it does not exist, using the specified request options and operation context. * * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return true if the container did not already exist and was created; otherwise, false. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean createIfNotExists(BlobRequestOptions options, OperationContext opContext) throws StorageException { boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext); if (exists) { return false; } else { try { this.create(options, opContext); return true; } catch (StorageException e) { if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT && StorageErrorCodeStrings.CONTAINER_ALREADY_EXISTS.equals(e.getErrorCode())) { return false; } else { throw e; } } } } /** * Deletes the container. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void delete() throws StorageException { this.delete(null /* accessCondition */, null /* options */, null /* opContext */); } /** * Deletes the container using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void delete(AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); ExecutionEngine.executeWithRetry(this.blobServiceClient, this, deleteImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest deleteImpl(final AccessCondition accessCondition, final BlobRequestOptions options) { final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.delete(container.getStorageUri().getPrimaryUri(), options.getTimeoutIntervalInMs(), accessCondition, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, -1L, null); } @Override public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { this.setNonExceptionedRetryableFailure(true); } return null; } }; return putRequest; } /** * Deletes the container if it exists. * * @return true if the container did not already exist and was created; otherwise, false. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean deleteIfExists() throws StorageException { return this.deleteIfExists(null /* accessCondition */, null /* options */, null /* opContext */); } /** * Deletes the container if it exists using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return true if the container existed and was deleted; otherwise, false. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean deleteIfExists(AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { boolean exists = this.exists(true /* primaryOnly */, accessCondition, options, opContext); if (exists) { try { this.delete(accessCondition, options, opContext); return true; } catch (StorageException e) { if (e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND && StorageErrorCodeStrings.CONTAINER_NOT_FOUND.equals(e.getErrorCode())) { return false; } else { throw e; } } } else { return false; } } /** * Downloads the container's attributes, which consist of metadata and properties. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void downloadAttributes() throws StorageException { this.downloadAttributes(null /* accessCondition */, null /* options */, null /* opContext */); } /** * Downloads the container's attributes, which consist of metadata and properties, using the specified request * options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void downloadAttributes(AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.downloadAttributesImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest downloadAttributesImpl( final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest getRequest = new StorageRequest( options, this.getStorageUri()) { @Override public void setRequestLocationMode() { this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY); } @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.getProperties(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), accessCondition, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, -1L, null); } @Override public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } // Set attributes final BlobContainerAttributes attributes = ContainerResponse.getAttributes(this.getConnection(), client.isUsePathStyleUris()); container.metadata = attributes.getMetadata(); container.properties = attributes.getProperties(); container.name = attributes.getName(); return null; } }; return getRequest; } /** * Downloads the permission settings for the container. * * @return A {@link BlobContainerPermissions} object that represents the container's permissions. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public BlobContainerPermissions downloadPermissions() throws StorageException { return this.downloadPermissions(null /* accessCondition */, null /* options */, null /* opContext */); } /** * Downloads the permissions settings for the container using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @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 BlobContainerPermissions} object that represents the container's permissions. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public BlobContainerPermissions downloadPermissions(AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, downloadPermissionsImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest downloadPermissionsImpl( final AccessCondition accessCondition, final BlobRequestOptions options) { final StorageRequest getRequest = new StorageRequest( options, this.getStorageUri()) { @Override public void setRequestLocationMode() { this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY); } @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.getAcl(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), accessCondition, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, -1L, null); } @Override public BlobContainerPermissions preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); } container.updatePropertiesFromResponse(this.getConnection()); final String aclString = ContainerResponse.getAcl(this.getConnection()); final BlobContainerPermissions containerAcl = getContainerAcl(aclString); return containerAcl; } @Override public BlobContainerPermissions postProcessResponse(HttpURLConnection connection, CloudBlobContainer container, CloudBlobClient client, OperationContext context, BlobContainerPermissions containerAcl) throws Exception { final BlobAccessPolicyResponse response = new BlobAccessPolicyResponse(connection.getInputStream()); for (final String key : response.getAccessIdentifiers().keySet()) { containerAcl.getSharedAccessPolicies().put(key, response.getAccessIdentifiers().get(key)); } return containerAcl; } }; return getRequest; } /** * Returns a value that indicates whether the container exists. * * @return true if the container exists, otherwise false. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean exists() throws StorageException { return this.exists(null /* accessCondition */, null /* options */, null /* opContext */); } /** * Returns a value that indicates whether the container exists, using the specified request options and operation * context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return true if the container exists, otherwise false. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean exists(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { return this.exists(false, accessCondition, options, opContext); } @DoesServiceRequest private boolean exists(final boolean primaryOnly, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.existsImpl(primaryOnly, accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest existsImpl(final boolean primaryOnly, final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest getRequest = new StorageRequest( options, this.getStorageUri()) { @Override public void setRequestLocationMode() { this.setRequestLocationMode(primaryOnly ? RequestLocationMode.PRIMARY_ONLY : RequestLocationMode.PRIMARY_OR_SECONDARY); } @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.getProperties(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), accessCondition, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, -1L, null); } @Override public Boolean preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { container.updatePropertiesFromResponse(this.getConnection()); return Boolean.valueOf(true); } else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Boolean.valueOf(false); } else { this.setNonExceptionedRetryableFailure(true); // return false instead of null to avoid SCA issues return false; } } }; return getRequest; } /** * Returns a shared access signature for the container. Note this does not contain the leading "?". * * @param policy * The access policy for the shared access signature. * @param groupPolicyIdentifier * A container-level access policy. * @return a shared access signature for the container. * @throws InvalidKeyException * @throws StorageException * @throws IllegalArgumentException */ public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier) throws InvalidKeyException, StorageException { if (!this.blobServiceClient.getCredentials().canCredentialsSignRequest()) { final String errorMessage = SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY; throw new IllegalArgumentException(errorMessage); } final String resourceName = this.getSharedAccessCanonicalName(); final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForBlob(policy, null /* SharedAccessBlobHeaders */, groupPolicyIdentifier, resourceName, this.blobServiceClient, null); final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignatureForBlob(policy, null /* SharedAccessBlobHeaders */, groupPolicyIdentifier, "c", signature); return builder.toString(); } /** * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this container. * * @param blobAddressUri * A String that represents the name of the blob, or the absolute URI to the blob. * * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudBlockBlob getBlockBlobReference(final String blobAddressUri) throws URISyntaxException, StorageException { Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); final StorageUri address = PathUtility.appendPathToUri(this.storageUri, blobAddressUri); return new CloudBlockBlob(address, this.blobServiceClient, this); } /** * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this container, using the * specified snapshot ID. * * @param blobAddressUri * A String that represents the name of the blob, or the absolute URI to the blob. * @param snapshotID * A String that represents the snapshot ID of the blob. * * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudBlockBlob getBlockBlobReference(final String blobAddressUri, final String snapshotID) throws URISyntaxException, StorageException { Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); final StorageUri address = PathUtility.appendPathToUri(this.storageUri, blobAddressUri); final CloudBlockBlob retBlob = new CloudBlockBlob(address, snapshotID, this.blobServiceClient); retBlob.setContainer(this); return retBlob; } /** * Returns a reference to a {@link CloudBlobDirectory} object that represents a virtual blob directory within this * container. * * @param relativeAddress * A String that represents the name of the virtual blob directory. * * @return A {@link CloudBlobDirectory} that represents a virtual blob directory within this container. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudBlobDirectory getDirectoryReference(final String relativeAddress) throws URISyntaxException, StorageException { Utility.assertNotNullOrEmpty("relativeAddress", relativeAddress); final StorageUri address = PathUtility.appendPathToUri(this.storageUri, relativeAddress); return new CloudBlobDirectory(address, null, this.blobServiceClient); } /** * Returns the metadata for the container. * * @return A java.util.HashMap object that represents the metadata for the container. */ public HashMap getMetadata() { return this.metadata; } /** * Returns the name of the container. * * @return A String that represents the name of the container. */ public String getName() { return this.name; } /** * Returns the list of URIs for all locations. * * @return A StorageUri that represents the list of URIs for all locations.. */ public final StorageUri getStorageUri() { return this.storageUri; } /** * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in this container. * * @param blobAddressUri * A String that represents the name of the blob, or the absolute URI to the blob. * * @return A {@link CloudPageBlob} object that represents a reference to the specified page blob. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudPageBlob getPageBlobReference(final String blobAddressUri) throws URISyntaxException, StorageException { Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); final StorageUri address = PathUtility.appendPathToUri(this.storageUri, blobAddressUri); return new CloudPageBlob(address, this.blobServiceClient, this); } /** * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in the directory, using the * specified snapshot ID. * * @param blobAddressUri * A String that represents the name of the blob, or the absolute URI to the blob. * @param snapshotID * A String that represents the snapshot ID of the blob. * * @return A {@link CloudPageBlob} object that represents a reference to the specified page blob. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public CloudPageBlob getPageBlobReference(final String blobAddressUri, final String snapshotID) throws URISyntaxException, StorageException { Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); final StorageUri address = PathUtility.appendPathToUri(this.storageUri, blobAddressUri); final CloudPageBlob retBlob = new CloudPageBlob(address, snapshotID, this.blobServiceClient); retBlob.setContainer(this); return retBlob; } /** * Returns the properties for the container. * * @return A {@link BlobContainerProperties} object that represents the properties for the container. */ public BlobContainerProperties getProperties() { return this.properties; } /** * Returns the Blob service client associated with this container. * * @return A {@link CloudBlobClient} object that represents the service client associated with this container. */ public CloudBlobClient getServiceClient() { return this.blobServiceClient; } /** * Returns the canonical name for shared access. * * @return the canonical name for shared access. */ private String getSharedAccessCanonicalName() { if (this.blobServiceClient.isUsePathStyleUris()) { return this.getUri().getPath(); } else { return PathUtility.getCanonicalPathFromCredentials(this.blobServiceClient.getCredentials(), this.getUri() .getPath()); } } /** * Returns the URI after applying the authentication transformation. * * @return A java.net.URI object that represents the URI after applying the authentication * transformation. * * @throws IllegalArgumentException * If an unexpected value is passed. * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ private StorageUri getTransformedAddress() throws URISyntaxException, StorageException { if (this.blobServiceClient.getCredentials().doCredentialsNeedTransformUri()) { if (this.getStorageUri().isAbsolute()) { return this.blobServiceClient.getCredentials().transformUri(this.storageUri); } else { final StorageException ex = Utility.generateNewUnexpectedStorageException(null); ex.getExtendedErrorInformation().setErrorMessage("Blob Object relative URIs not supported."); throw ex; } } else { return this.storageUri; } } /** * Returns the URI for this container. * * @return The absolute URI to the container. */ public URI getUri() { return this.storageUri.getPrimaryUri(); } /** * Returns an enumerable collection of blob items for the container. * * @return An enumerable collection of {@link ListBlobItem} objects retrieved lazily that represents the items in * this container. * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public Iterable listBlobs() throws StorageException { return this.listBlobs(null, false, EnumSet.noneOf(BlobListingDetails.class), null, null); } /** * Returns an enumerable collection of blob items for the container whose names begin with the specified prefix. * * @param prefix * A String that represents the blob name prefix. This value must be preceded either by the * name of the container or by the absolute path to the container. * * @return An enumerable collection of {@link ListBlobItem} objects retrieved lazily that represents the items whose * names begin with * the specified prefix in this container. * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public Iterable listBlobs(final String prefix) throws StorageException { return this.listBlobs(prefix, false, EnumSet.noneOf(BlobListingDetails.class), null, null); } /** * Returns an enumerable collection of blob items whose names begin with the specified prefix, using the specified * flat or hierarchical option, listing details options, request options, and operation context. * * @param prefix * A String that represents the blob name prefix. This value must be preceded either by the * name of the container or by the absolute path to the container. * @param useFlatBlobListing * true to indicate that the returned list will be flat; false to indicate that * the returned list will be hierarchical. * @param listingDetails * A java.util.EnumSet object that contains {@link BlobListingDetails} values that indicate * whether snapshots, metadata, and/or uncommitted blocks are returned. Committed blocks are always * returned. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @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 ListBlobItem} objects retrieved lazily that represent the block items * whose names begin * with the specified prefix in this directory. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ @DoesServiceRequest public Iterable listBlobs(final String prefix, final boolean useFlatBlobListing, final EnumSet listingDetails, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); if (!useFlatBlobListing && listingDetails != null && listingDetails.contains(BlobListingDetails.SNAPSHOTS)) { throw new IllegalArgumentException(SR.SNAPSHOT_LISTING_ERROR); } SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest(); return new LazySegmentedIterable( this.listBlobsSegmentedImpl(prefix, useFlatBlobListing, listingDetails, -1, options, segmentedRequest), this.blobServiceClient, this, options.getRetryPolicyFactory(), opContext); } /** * Returns a result segment of an enumerable collection of blob items in the container. * * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of * {@link ListBlobItem} objects that represent the blob items in the container. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public ResultSegment listBlobsSegmented() throws StorageException { return this.listBlobsSegmented(null, false, EnumSet.noneOf(BlobListingDetails.class), -1, null, null, null); } /** * Returns a result segment containing a collection of blob items whose names begin with the specified prefix. * * @param prefix * A String that represents the prefix of the blob name. * * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of * {@link ListBlobItem} objects that represent the blob items whose names begin with the specified prefix in * the container. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public ResultSegment listBlobsSegmented(final String prefix) throws StorageException { return this.listBlobsSegmented(prefix, false, EnumSet.noneOf(BlobListingDetails.class), -1, null, null, null); } /** * Returns a result segment containing a collection of blob items whose names begin with the specified prefix, using * the specified flat or hierarchical option, listing details options, request options, and operation context. * * @param prefix * A String that represents the prefix of the blob name. * @param useFlatBlobListing * true to indicate that the returned list will be flat; false to indicate that * the returned list will be hierarchical. * @param listingDetails * A java.util.EnumSet object that contains {@link BlobListingDetails} values that indicate * whether snapshots, metadata, and/or uncommitted blocks are returned. Committed blocks are always * returned. * @param maxResults * The maximum number of results to retrieve. * @param continuationToken * A {@link ResultContinuation} object that represents a continuation token returned by a previous * listing operation. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of * {@link ListBlobItem} objects that represent the block items whose names begin with the specified prefix * in the container. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public ResultSegment listBlobsSegmented(final String prefix, final boolean useFlatBlobListing, final EnumSet listingDetails, final int maxResults, final ResultContinuation continuationToken, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); Utility.assertContinuationType(continuationToken, ResultContinuationType.BLOB); if (!useFlatBlobListing && listingDetails != null && listingDetails.contains(BlobListingDetails.SNAPSHOTS)) { throw new IllegalArgumentException(SR.SNAPSHOT_LISTING_ERROR); } SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest(); segmentedRequest.setToken(continuationToken); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.listBlobsSegmentedImpl(prefix, useFlatBlobListing, listingDetails, maxResults, options, segmentedRequest), options .getRetryPolicyFactory(), opContext); } private StorageRequest> listBlobsSegmentedImpl( final String prefix, final boolean useFlatBlobListing, final EnumSet listingDetails, final int maxResults, final BlobRequestOptions options, final SegmentedStorageRequest segmentedRequest) throws StorageException { Utility.assertContinuationType(segmentedRequest.getToken(), ResultContinuationType.BLOB); Utility.assertNotNull("options", options); final String delimiter = useFlatBlobListing ? null : this.blobServiceClient.getDirectoryDelimiter(); final BlobListingContext listingContext = new BlobListingContext(prefix, maxResults, delimiter, listingDetails); final StorageRequest> getRequest = new StorageRequest>( options, this.getStorageUri()) { @Override public void setRequestLocationMode() { this.setRequestLocationMode(Utility.getListingLocationMode(segmentedRequest.getToken())); } @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { listingContext.setMarker(segmentedRequest.getToken() != null ? segmentedRequest.getToken() .getNextMarker() : null); return BlobRequest.list(container.getTransformedAddress().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), listingContext, options, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, -1L, null); } @Override public ResultSegment preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); } return null; } @Override public ResultSegment postProcessResponse(HttpURLConnection connection, CloudBlobContainer container, CloudBlobClient client, OperationContext context, ResultSegment storageObject) throws Exception { final ListBlobsResponse response = new ListBlobsResponse(connection.getInputStream()); response.parseResponse(client, container); ResultContinuation newToken = null; if (response.getNextMarker() != null) { newToken = new ResultContinuation(); newToken.setNextMarker(response.getNextMarker()); newToken.setContinuationType(ResultContinuationType.BLOB); newToken.setTargetLocation(this.getResult().getTargetLocation()); } final ResultSegment resSegment = new ResultSegment(response.getBlobs( client, container), maxResults, newToken); // Important for listBlobs because this is required by the lazy iterator between executions. segmentedRequest.setToken(resSegment.getContinuationToken()); return resSegment; } }; return getRequest; } /** * Returns an enumerable collection of containers for the service client associated with this container. * * @return An enumerable collection of {@link CloudBlobContainer} objects retrieved lazily that represent the * containers for the * service client associated with this container. * @throws StorageException */ @DoesServiceRequest public Iterable listContainers() throws StorageException { return this.blobServiceClient.listContainers(); } /** * Returns an enumerable collection of containers whose names begin with the specified prefix for the service client * associated with this container. * * @param prefix * A String that represents the container name prefix. * * @return An enumerable collection of {@link CloudBlobContainer} objects retrieved lazily that represent the * containers whose names * begin with the specified prefix for the service client associated with this container. * @throws StorageException */ @DoesServiceRequest public Iterable listContainers(final String prefix) throws StorageException { return this.blobServiceClient.listContainers(prefix); } /** * Returns an enumerable collection of containers whose names begin with the specified prefix for the service client * associated with this container, using the specified details setting, request options, and operation context. * * @param prefix * A String that represents the container name prefix. * @param detailsIncluded * A {@link ContainerListingDetails} value that indicates whether container metadata will be returned. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @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 CloudBlobContainer} objects retrieved lazily that represents the * containers for the * service client associated with this container. * @throws StorageException */ @DoesServiceRequest public Iterable listContainers(final String prefix, final ContainerListingDetails detailsIncluded, final BlobRequestOptions options, final OperationContext opContext) throws StorageException { return this.blobServiceClient.listContainers(prefix, detailsIncluded, options, opContext); } /** * Returns a result segment of an enumerable collection of containers for the service client associated with this * container. * * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of * {@link CloudBlobContainer} objects that represent the containers for the service client associated with * this container. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public ResultSegment listContainersSegmented() throws StorageException { return this.blobServiceClient.listContainersSegmented(); } /** * Returns a result segment of an enumerable collection of containers whose names begin with the specified prefix * for the service client associated with this container. * * @param prefix * A String that represents the blob name prefix. * * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of * {@link CloudBlobContainer} objects that represent the containers whose names begin with the specified * prefix for the service client associated with this container. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public ResultSegment listContainersSegmented(final String prefix) throws StorageException { return this.blobServiceClient.listContainersSegmented(prefix); } /** * Returns a result segment containing a collection of containers whose names begin with the specified prefix for * the service client associated with this container, using the specified listing details options, request options, * and operation context. * * @param prefix * A String that represents the prefix of the container name. * @param detailsIncluded * A {@link ContainerListingDetails} object that indicates whether metadata is included. * @param maxResults * The maximum number of results to retrieve. * @param continuationToken * A {@link ResultContinuation} object that represents a continuation token returned by a previous * listing operation. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of * {@link CloudBlobContainer} objects that represent the containers whose names begin with the specified * prefix for the service client associated with this container. * * @throws StorageException * If a storage service error occurred. * */ @DoesServiceRequest public ResultSegment listContainersSegmented(final String prefix, final ContainerListingDetails detailsIncluded, final int maxResults, final ResultContinuation continuationToken, final BlobRequestOptions options, final OperationContext opContext) throws StorageException { return this.blobServiceClient.listContainersSegmented(prefix, detailsIncluded, maxResults, continuationToken, options, opContext); } /** * Parse Uri for SAS (Shared access signature) information. * * Validate that no other query parameters are passed in. Any SAS information will be recorded as corresponding * credentials instance. If existingClient is passed in, any SAS information found will not be supported. Otherwise * a new client is created based on SAS information or as anonymous credentials. * * @param completeUri * The complete Uri. * @param existingClient * The client to use. * @param usePathStyleUris * If true, path style Uris are used. * @throws URISyntaxException * @throws StorageException */ private void parseQueryAndVerify(final StorageUri completeUri, final CloudBlobClient existingClient, final boolean usePathStyleUris) throws URISyntaxException, StorageException { Utility.assertNotNull("completeUri", completeUri); if (!completeUri.isAbsolute()) { final String errorMessage = String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()); throw new IllegalArgumentException(errorMessage); } this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri); final HashMap queryParameters = PathUtility.parseQueryString(completeUri.getQuery()); final StorageCredentialsSharedAccessSignature sasCreds = SharedAccessSignatureHelper .parseQuery(queryParameters); if (sasCreds == null) { return; } final Boolean sameCredentials = existingClient == null ? false : Utility.areCredentialsEqual(sasCreds, existingClient.getCredentials()); if (existingClient == null || !sameCredentials) { this.blobServiceClient = new CloudBlobClient(new URI(PathUtility.getServiceClientBaseAddress(this.getUri(), usePathStyleUris)), sasCreds); } if (existingClient != null && !sameCredentials) { this.blobServiceClient.setSingleBlobPutThresholdInBytes(existingClient.getSingleBlobPutThresholdInBytes()); this.blobServiceClient.setConcurrentRequestCount(existingClient.getConcurrentRequestCount()); this.blobServiceClient.setDirectoryDelimiter(existingClient.getDirectoryDelimiter()); this.blobServiceClient.setRetryPolicyFactory(existingClient.getRetryPolicyFactory()); this.blobServiceClient.setTimeoutInMs(existingClient.getTimeoutInMs()); this.blobServiceClient.setLocationMode(existingClient.getLocationMode()); } } void updatePropertiesFromResponse(HttpURLConnection request) { // ETag this.getProperties().setEtag(request.getHeaderField(Constants.HeaderConstants.ETAG)); // Last Modified if (0 != request.getLastModified()) { final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US); lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE); lastModifiedCalendar.setTime(new Date(request.getLastModified())); this.getProperties().setLastModified(lastModifiedCalendar.getTime()); } } /** * Sets the metadata for the container. * * @param metadata * A java.util.HashMap object that represents the metadata being assigned to the container. */ public void setMetadata(final HashMap metadata) { this.metadata = metadata; } /** * Sets the name of the container. * * @param name * A String that represents the name being assigned to the container. */ protected void setName(final String name) { this.name = name; } /** * Sets the list of URIs for all locations. * * @param storageUri * A StorageUri that represents the list of URIs for all locations. */ protected void setStorageUri(final StorageUri storageUri) { this.storageUri = storageUri; } /** * Sets the properties for the container. * * @param properties * A {@link BlobContainerProperties} object that represents the properties being assigned to the * container. */ protected void setProperties(final BlobContainerProperties properties) { this.properties = properties; } /** * Uploads the container's metadata. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void uploadMetadata() throws StorageException { this.uploadMetadata(null /* accessCondition */, null /* options */, null /* opContext */); } /** * Uploads the container's metadata using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void uploadMetadata(AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.uploadMetadataImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); } @DoesServiceRequest private StorageRequest uploadMetadataImpl( final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.setMetadata(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), accessCondition, context); } @Override public void setHeaders(HttpURLConnection connection, CloudBlobContainer container, OperationContext context) { ContainerRequest.addMetadata(connection, container.metadata, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, 0L, null); } @Override public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); } container.updatePropertiesFromResponse(this.getConnection()); return null; } }; return putRequest; } /** * Uploads the container's permissions. * * @param permissions * A {@link BlobContainerPermissions} object that represents the permissions to upload. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void uploadPermissions(final BlobContainerPermissions permissions) throws StorageException { this.uploadPermissions(permissions, null /* accessCondition */, null /* options */, null /* opContext */); } /** * Uploads the container's permissions using the specified request options and operation context. * * @param permissions * A {@link BlobContainerPermissions} object that represents the permissions to upload. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public void uploadPermissions(final BlobContainerPermissions permissions, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); ExecutionEngine.executeWithRetry(this.blobServiceClient, this, uploadPermissionsImpl(permissions, accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest uploadPermissionsImpl( final BlobContainerPermissions permissions, final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { try { final StringWriter outBuffer = new StringWriter(); ContainerRequest.writeSharedAccessIdentifiersToStream(permissions.getSharedAccessPolicies(), outBuffer); final byte[] aclBytes = outBuffer.toString().getBytes(Constants.UTF8_CHARSET); final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { this.setSendStream(new ByteArrayInputStream(aclBytes)); this.setLength((long) aclBytes.length); return ContainerRequest.setAcl(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), permissions.getPublicAccess(), accessCondition, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, aclBytes.length, null); } @Override public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } container.updatePropertiesFromResponse(this.getConnection()); return null; } }; return putRequest; } catch (final IllegalArgumentException e) { StorageException translatedException = StorageException.translateException(null, e, null); throw translatedException; } catch (final XMLStreamException e) { // The request was not even made. There was an error while trying to read the permissions. Just throw. StorageException translatedException = StorageException.translateException(null, e, null); throw translatedException; } catch (UnsupportedEncodingException e) { // The request was not even made. There was an error while trying to read the permissions. Just throw. StorageException translatedException = StorageException.translateException(null, e, null); throw translatedException; } } /** * Acquires a new lease on the container with the specified lease time and proposed lease ID. * * @param leaseTimeInSeconds * Specifies the span of time for which to acquire the lease, in seconds. * If null, an infinite lease will be acquired. If not null, the value must be greater than * zero. * * @param proposedLeaseId * A String that represents the proposed lease ID for the new lease, * or null if no lease ID is proposed. * * @return A String that represents the lease ID. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId) throws StorageException { return this.acquireLease(leaseTimeInSeconds, proposedLeaseId, null /* accessCondition */, null /* options */, null /* opContext */); } /** * Acquires a new lease on the container with the specified lease time, proposed lease ID, request * options, and operation context. * * @param leaseTimeInSeconds * Specifies the span of time for which to acquire the lease, in seconds. * If null, an infinite lease will be acquired. If not null, the value must be greater than * zero. * * @param proposedLeaseId * A String that represents the proposed lease ID for the new lease, * or null if no lease ID is proposed. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. * * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client * ({@link CloudBlobClient}). * * @param opContext * An {@link OperationContext} object that represents the context for the current operation. The context * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A String that represents the lease ID. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.acquireLeaseImpl(leaseTimeInSeconds, proposedLeaseId, accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest acquireLeaseImpl( final Integer leaseTimeInSeconds, final String proposedLeaseId, final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.lease(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), LeaseAction.ACQUIRE, leaseTimeInSeconds, proposedLeaseId, null /* breakPeriodInSeconds */, accessCondition, options, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, 0L, null); } @Override public String preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { this.setNonExceptionedRetryableFailure(true); return null; } container.updatePropertiesFromResponse(this.getConnection()); return BlobResponse.getLeaseID(this.getConnection(), context); } }; return putRequest; } /** * Renews an existing lease with the specified access conditions. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the container. The lease * ID is required to be set with an access condition. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void renewLease(final AccessCondition accessCondition) throws StorageException { this.renewLease(accessCondition, null /* options */, null /* opContext */); } /** * Renews an existing lease with the specified access conditions, request options, and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is * required to be set with an access condition. * * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client * ({@link CloudBlobClient}). * * @param opContext * An {@link OperationContext} object that represents the context for the current operation. The context * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void renewLease(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("accessCondition", accessCondition); Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.renewLeaseImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest renewLeaseImpl( final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.lease(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), LeaseAction.RENEW, null /* leaseTimeInSeconds */, null /* proposedLeaseId */, null /* breakPeriodInseconds */, accessCondition, options, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, 0L, null); } @Override public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } container.updatePropertiesFromResponse(this.getConnection()); return null; } }; return putRequest; } /** * Releases the lease on the container. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is * required to be set with an access condition. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void releaseLease(final AccessCondition accessCondition) throws StorageException { this.releaseLease(accessCondition, null /* options */, null /* opContext */); } /** * Releases the lease on the container using the specified access conditions, request options, and operation * context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is * required to be set with an access condition. * * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client * ({@link CloudBlobClient}). * * @param opContext * An {@link OperationContext} object that represents the context for the current operation. The context * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void releaseLease(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("accessCondition", accessCondition); Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.releaseLeaseImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest releaseLeaseImpl( final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.lease(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), LeaseAction.RELEASE, null, null, null, accessCondition, options, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, 0L, null); } @Override public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } container.updatePropertiesFromResponse(this.getConnection()); return null; } }; return putRequest; } /** * Breaks the lease and ensures that another client cannot acquire a new lease until the current lease * period has expired. * * @param breakPeriodInSeconds * Specifies the time to wait, in seconds, until the current lease is broken. * If null, the break period is the remainder of the current lease, or zero for infinite leases. * * @return The time, in seconds, remaining in the lease period. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final long breakLease(final Integer breakPeriodInSeconds) throws StorageException { return this.breakLease(breakPeriodInSeconds, null /* accessCondition */, null, null); } /** * Breaks the existing lease, using the specified request options and operation context, and ensures that * another client cannot acquire a new lease until the current lease period has expired. * * @param breakPeriodInSeconds * Specifies the time to wait, in seconds, until the current lease is broken. * If null, the break period is the remainder of the current lease, or zero for infinite leases. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client * ({@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. The context * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return The time, in seconds, remaining in the lease period. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final long breakLease(final Integer breakPeriodInSeconds, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (breakPeriodInSeconds != null) { Utility.assertGreaterThanOrEqual("breakPeriodInSeconds", breakPeriodInSeconds, 0); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.breakLeaseImpl(breakPeriodInSeconds, accessCondition, options), options.getRetryPolicyFactory(), opContext); } private final StorageRequest breakLeaseImpl( final Integer breakPeriodInSeconds, final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest putCmd = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.lease(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), LeaseAction.BREAK, null, null, breakPeriodInSeconds, accessCondition, options, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, 0L, null); } @Override public Long preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { this.setNonExceptionedRetryableFailure(true); return -1L; } container.updatePropertiesFromResponse(this.getConnection()); final String leaseTime = BlobResponse.getLeaseTime(this.getConnection(), context); return Utility.isNullOrEmpty(leaseTime) ? -1L : Long.parseLong(leaseTime); } }; return putCmd; } /** * Changes the existing lease ID to the proposed lease ID. * * @param proposedLeaseId * A String that represents the proposed lease ID for the new lease, * or null if no lease ID is proposed. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is * required to be set with an access condition. * @return A String that represents the new lease ID. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final String changeLease(final String proposedLeaseId, final AccessCondition accessCondition) throws StorageException { return this.changeLease(proposedLeaseId, accessCondition, null, null); } /** * Changes the existing lease ID to the proposed lease Id with the specified access conditions, request options, * and operation context. * * @param proposedLeaseId * A String that represents the proposed lease ID for the new lease. This cannot be null. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is * required to be set with an access condition. * * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * null will use the default request options from the associated service client * ({@link CloudBlobClient}). * * @param opContext * An {@link OperationContext} object that represents the context for the current operation. The context * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * @return A String that represents the new lease ID. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final String changeLease(final String proposedLeaseId, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("proposedLeaseId", proposedLeaseId); Utility.assertNotNull("accessCondition", accessCondition); Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.applyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.changeLeaseImpl(proposedLeaseId, accessCondition, options), options.getRetryPolicyFactory(), opContext); } private final StorageRequest changeLeaseImpl( final String proposedLeaseId, final AccessCondition accessCondition, final BlobRequestOptions options) throws StorageException { final StorageRequest putRequest = new StorageRequest( options, this.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return ContainerRequest.lease(container.getStorageUri().getUri(this.getCurrentLocation()), options.getTimeoutIntervalInMs(), LeaseAction.CHANGE, null, proposedLeaseId, null, accessCondition, options, context); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobAndQueueRequest(connection, client, 0L, null); } @Override public String preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } container.updatePropertiesFromResponse(this.getConnection()); return BlobResponse.getLeaseID(this.getConnection(), context); } }; return putRequest; } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy