Java Code Examples for com.microsoft.azure.storage.core.Utility#generateNewUnexpectedStorageException()

The following examples show how to use com.microsoft.azure.storage.core.Utility#generateNewUnexpectedStorageException() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CloudQueueMessage.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the content of the message as a string.
 * 
 * @return A <code>String</code> which contains the content of the message.
 * 
 * @throws StorageException
 *         If a storage service error occurred.
 */
public final String getMessageContentAsString() throws StorageException {
    if (this.messageType == QueueMessageType.RAW_STRING) {
        return this.messageContent;
    }
    else {
        if (Utility.isNullOrEmpty(this.messageContent)) {
            return null;
        }

        try {
            return new String(Base64.decode(this.messageContent), Constants.UTF8_CHARSET);
        }
        catch (final UnsupportedEncodingException e) {
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }
}
 
Example 2
Source File: CloudQueueMessage.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the content of the message as a byte array.
 * 
 * @return A <code>byte</code> array which contains the content of the message.
 * 
 * @throws StorageException
 *         If a storage service error occurred.
 */
public final byte[] getMessageContentAsByte() throws StorageException {
    if (Utility.isNullOrEmpty(this.messageContent)) {
        return new byte[0];
    }

    if (this.messageType == QueueMessageType.RAW_STRING) {
        try {
            return this.messageContent.getBytes(Constants.UTF8_CHARSET);
        }
        catch (final UnsupportedEncodingException e) {
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }
    else {
        return Base64.decode(this.messageContent);
    }
}
 
Example 3
Source File: FileResponse.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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
 */
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;
}
 
Example 4
Source File: FileRequest.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the share Uri query builder.
 * 
 * A <CODE>UriQueryBuilder</CODE> for the share.
 * 
 * @throws StorageException
 */
private static UriQueryBuilder getDirectoryUriQueryBuilder() throws StorageException {
    final UriQueryBuilder uriBuilder = new UriQueryBuilder();
    try {
        uriBuilder.add(Constants.QueryConstants.RESOURCETYPE, "directory");
    }
    catch (final IllegalArgumentException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
    return uriBuilder;
}
 
Example 5
Source File: CloudQueue.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials) 
        throws StorageException {
    Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.queueServiceClient = new CloudQueueClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getContainerNameFromUri(storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example 6
Source File: CloudTable.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */  
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials) 
        throws StorageException {
    Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.tableServiceClient = new CloudTableClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getTableNameFromUri(storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example 7
Source File: CloudFile.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 * @throws URISyntaxException 
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException, URISyntaxException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.fileServiceClient = new CloudFileClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getFileNameFromURI(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }

    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(Constants.QueryConstants.SHARE_SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.getShare().snapshotID = snapshotIDs[0];
    }
}
 
Example 8
Source File: FileOutputStream.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a new instance of the FileOutputStream class.
 * 
 * @param parentFile
 *            A {@link CloudFile} object which represents the file that this stream is associated with.
 * @param length
 *            A <code>long</code> which represents the length of the file in bytes.
 * @param accessCondition
 *            An {@link AccessCondition} object which represents the access conditions for the file.
 * @param options
 *            A {@link FileRequestOptions} object which specifies any additional options for the request.
 * @param opContext
 *            An {@link OperationContext} object which is used to track the execution of the operation
 * 
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
@DoesServiceRequest
protected FileOutputStream(final CloudFile parentFile, final long length, final AccessCondition accessCondition,
        final FileRequestOptions options, final OperationContext opContext) throws StorageException {
    this.accessCondition = accessCondition;
    this.parentFileRef = parentFile;
    this.options = new FileRequestOptions(options);
    this.outBuffer = new ByteArrayOutputStream();
    this.opContext = opContext;
    this.streamFaulted = false;

    if (this.options.getConcurrentRequestCount() < 1) {
        throw new IllegalArgumentException("ConcurrentRequestCount");
    }

    if (this.options.getStoreFileContentMD5()) {
        try {
            this.md5Digest = MessageDigest.getInstance("MD5");
        }
        catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    // V2 cachedThreadPool for perf.
    this.threadExecutor = Executors.newFixedThreadPool(this.options.getConcurrentRequestCount());
    this.completionService = new ExecutorCompletionService<Void>(this.threadExecutor);
    this.internalWriteThreshold = (int) Math.min(this.parentFileRef.getStreamWriteSizeInBytes(), length);
}
 
Example 9
Source File: CloudFileShare.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);

    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(Constants.QueryConstants.SHARE_SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.snapshotID = snapshotIDs[0];
    }

    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.fileServiceClient = new CloudFileClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getShareNameFromUri(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example 10
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the container Uri query builder.
 * 
 * A <CODE>UriQueryBuilder</CODE> for the container.
 * 
 * @throws StorageException
 */
private static UriQueryBuilder getContainerUriQueryBuilder() throws StorageException {
    final UriQueryBuilder uriBuilder = new UriQueryBuilder();
    try {
        uriBuilder.add(Constants.QueryConstants.RESOURCETYPE, "container");
    }
    catch (final IllegalArgumentException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
    return uriBuilder;
}
 
Example 11
Source File: FileRequest.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the share Uri query builder.
 * 
 * A <CODE>UriQueryBuilder</CODE> for the share.
 * 
 * @throws StorageException
 */
private static UriQueryBuilder getShareUriQueryBuilder() throws StorageException {
    final UriQueryBuilder uriBuilder = new UriQueryBuilder();
    try {
        uriBuilder.add(Constants.QueryConstants.RESOURCETYPE, "share");
    }
    catch (final IllegalArgumentException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
    return uriBuilder;
}
 
Example 12
Source File: CloudFileDirectory.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 * @throws URISyntaxException 
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException, URISyntaxException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.fileServiceClient = new CloudFileClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getDirectoryNameFromURI(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }

    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(Constants.QueryConstants.SHARE_SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.getShare().snapshotID = snapshotIDs[0];
    }
}
 
Example 13
Source File: BlobResponse.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the BlobContainerAttributes 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 BlobContainerAttributes from the given request.
 * @throws StorageException
 */
public static BlobContainerAttributes getBlobContainerAttributes(final HttpURLConnection request,
        final boolean usePathStyleUris) throws StorageException {
    final BlobContainerAttributes containerAttributes = new BlobContainerAttributes();
    URI tempURI;
    try {
        tempURI = PathUtility.stripSingleURIQueryAndFragment(request.getURL().toURI());
    }
    catch (final URISyntaxException e) {
        final StorageException wrappedUnexpectedException = Utility.generateNewUnexpectedStorageException(e);
        throw wrappedUnexpectedException;
    }

    containerAttributes.setName(PathUtility.getContainerNameFromUri(tempURI, usePathStyleUris));

    final BlobContainerProperties containerProperties = containerAttributes.getProperties();
    containerProperties.setEtag(BaseResponse.getEtag(request));
    containerProperties.setLastModified(new Date(request.getLastModified()));
    containerAttributes.setMetadata(getMetadata(request));

    containerProperties.setLeaseStatus(getLeaseStatus(request));
    containerProperties.setLeaseState(getLeaseState(request));
    containerProperties.setLeaseDuration(getLeaseDuration(request));

    containerProperties.setPublicAccess(getPublicAccessLevel(request));

    return containerAttributes;
}
 
Example 14
Source File: CloudBlob.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());

    final String[] snapshotIDs = queryParameters.get(BlobConstants.SNAPSHOT);
    if (snapshotIDs != null && snapshotIDs.length > 0) {
        this.snapshotID = snapshotIDs[0];
    }
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(queryParameters);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.blobServiceClient = new CloudBlobClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getBlobNameFromURI(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example 15
Source File: BlobOutputStream.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a new instance of the BlobOutputStream class.
 * 
 * @param parentBlob
 *            A {@link CloudBlob} object which represents the blob that this stream is associated with.
 * @param accessCondition
 *            An {@link AccessCondition} object which represents the access conditions for the blob.
 * @param options
 *            A {@link BlobRequestOptions} object which specifies any additional options for the request.
 * @param opContext
 *            An {@link OperationContext} object which is used to track the execution of the operation.
 * 
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
private BlobOutputStream(final CloudBlob parentBlob, final AccessCondition accessCondition,
        final BlobRequestOptions options, final OperationContext opContext) throws StorageException {
    this.accessCondition = accessCondition;
    this.parentBlobRef = parentBlob;
    this.parentBlobRef.assertCorrectBlobType();
    this.options = new BlobRequestOptions(options);
    this.outBuffer = new ByteArrayOutputStream();
    this.opContext = opContext;

    if (this.options.getConcurrentRequestCount() < 1) {
        throw new IllegalArgumentException("ConcurrentRequestCount");
    }
    
    this.futureSet = Collections.newSetFromMap(new ConcurrentHashMap<Future<Void>, Boolean>(
            this.options.getConcurrentRequestCount() == null ? 1 : this.options.getConcurrentRequestCount() * 2));

    if (this.options.getStoreBlobContentMD5()) {
        try {
            this.md5Digest = MessageDigest.getInstance("MD5");
        }
        catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    // V2 cachedThreadPool for perf.        
    this.threadExecutor = new ThreadPoolExecutor(
            this.options.getConcurrentRequestCount(),
            this.options.getConcurrentRequestCount(),
            10, 
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    this.completionService = new ExecutorCompletionService<Void>(this.threadExecutor);
}
 
Example 16
Source File: CloudBlobContainer.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.
 * 
 * @param completeUri
 *            A {@link StorageUri} object which represents the complete URI.
 * @param credentials
 *            A {@link StorageCredentials} object used to authenticate access.
 * @throws StorageException
 *             If a storage service error occurred.
 */
private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)
        throws StorageException {
   Utility.assertNotNull("completeUri", completeUri);

    if (!completeUri.isAbsolute()) {
        throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));
    }

    this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);
    
    final StorageCredentialsSharedAccessSignature parsedCredentials = 
            SharedAccessSignatureHelper.parseQuery(completeUri);

    if (credentials != null && parsedCredentials != null) {
        throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);
    }

    try {
        final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());
        this.blobServiceClient = new CloudBlobClient(PathUtility.getServiceClientBaseAddress(
                this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);
        this.name = PathUtility.getContainerNameFromUri(this.storageUri.getPrimaryUri(), usePathStyleUris);
    }
    catch (final URISyntaxException e) {
        throw Utility.generateNewUnexpectedStorageException(e);
    }
}
 
Example 17
Source File: FileInputStream.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes a new instance of the FileInputStream class.
 * 
 * @param parentFile
 *            A {@link CloudFile} object which represents the file that this stream is associated with.
 * @param accessCondition
 *            An {@link AccessCondition} object which represents the access conditions for the file.
 * @param options
 *            A {@link FileRequestOptions} object which represents that specifies any additional options for the
 *            request.
 * @param opContext
 *            An {@link OperationContext} object which is used to track the execution of the operation.
 * 
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
@DoesServiceRequest
protected FileInputStream(final CloudFile parentFile, final AccessCondition accessCondition,
        final FileRequestOptions options, final OperationContext opContext) throws StorageException {
    this.parentFileRef = parentFile;
    this.options = new FileRequestOptions(options);
    this.opContext = opContext;
    this.streamFaulted = false;
    this.currentAbsoluteReadPosition = 0;
    this.readSize = parentFile.getStreamMinimumReadSizeInBytes();

    if (options.getUseTransactionalContentMD5() && this.readSize > 4 * Constants.MB) {
        throw new IllegalArgumentException(SR.INVALID_RANGE_CONTENT_MD5_HEADER);
    }

    parentFile.downloadAttributes(accessCondition, this.options, this.opContext);

    this.retrievedContentMD5Value = parentFile.getProperties().getContentMD5();

    // Will validate it if it was returned
    this.validateFileMd5 = !options.getDisableContentMD5Validation()
            && !Utility.isNullOrEmpty(this.retrievedContentMD5Value);

    String previousLeaseId = null;
    if (accessCondition != null) {
        previousLeaseId = accessCondition.getLeaseID();
    }

    this.accessCondition = AccessCondition.generateIfMatchCondition(this.parentFileRef.getProperties().getEtag());
    this.accessCondition.setLeaseID(previousLeaseId);

    this.streamLength = parentFile.getProperties().getLength();

    if (this.validateFileMd5) {
        try {
            this.md5Digest = MessageDigest.getInstance("MD5");
        }
        catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    this.reposition(0);
}
 
Example 18
Source File: BlobInputStream.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes a new instance of the BlobInputStream class.
 * 
 * @param parentBlob
 *            A {@link CloudBlob} object which represents the blob that this stream is associated with.
 * @param accessCondition
 *            An {@link AccessCondition} object which represents the access conditions for the blob.
 * @param options
 *            A {@link BlobRequestOptions} object which represents that specifies any additional options for the
 *            request.
 * @param opContext
 *            An {@link OperationContext} object which is used to track the execution of the operation.
 * 
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
@DoesServiceRequest
protected BlobInputStream(final CloudBlob parentBlob, final AccessCondition accessCondition,
        final BlobRequestOptions options, final OperationContext opContext) throws StorageException {
    this.parentBlobRef = parentBlob;
    this.parentBlobRef.assertCorrectBlobType();
    this.options = new BlobRequestOptions(options);
    this.opContext = opContext;
    this.streamFaulted = false;
    this.currentAbsoluteReadPosition = 0;
    this.readSize = parentBlob.getStreamMinimumReadSizeInBytes();

    if (options.getUseTransactionalContentMD5() && this.readSize > 4 * Constants.MB) {
        throw new IllegalArgumentException(SR.INVALID_RANGE_CONTENT_MD5_HEADER);
    }

    parentBlob.downloadAttributes(accessCondition, this.options, this.opContext);

    this.retrievedContentMD5Value = parentBlob.getProperties().getContentMD5();

    // Will validate it if it was returned
    this.validateBlobMd5 = !options.getDisableContentMD5Validation()
            && !Utility.isNullOrEmpty(this.retrievedContentMD5Value);

    // Validates the first option, and sets future requests to use if match
    // request option.

    // If there is an existing conditional validate it, as we intend to
    // replace if for future requests.
    String previousLeaseId = null;
    if (accessCondition != null) {
        previousLeaseId = accessCondition.getLeaseID();

        if (!accessCondition.verifyConditional(this.parentBlobRef.getProperties().getEtag(), this.parentBlobRef
                .getProperties().getLastModified())) {
            throw new StorageException(StorageErrorCode.CONDITION_FAILED.toString(),
                    SR.INVALID_CONDITIONAL_HEADERS, HttpURLConnection.HTTP_PRECON_FAILED, null, null);
        }
    }

    this.accessCondition = AccessCondition.generateIfMatchCondition(this.parentBlobRef.getProperties().getEtag());
    this.accessCondition.setLeaseID(previousLeaseId);

    this.streamLength = parentBlob.getProperties().getLength();

    if (this.validateBlobMd5) {
        try {
            this.md5Digest = MessageDigest.getInstance("MD5");
        }
        catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    this.reposition(0);
}