com.microsoft.azure.storage.core.Utility Java Examples

The following examples show how to use com.microsoft.azure.storage.core.Utility. 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: BlobInputStream.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Dispatches a read operation of N bytes. When using sparspe page blobs the page ranges are evaluated and zero
 * bytes may be generated on the client side for some ranges that do not exist.
 * 
 * @param readLength
 *            An <code>int</code> which represents the number of bytes to read.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 */
@DoesServiceRequest
private synchronized void dispatchRead(final int readLength) throws IOException {
    try {
        final byte[] byteBuffer = new byte[readLength];

        this.parentBlobRef.downloadRangeInternal(this.currentAbsoluteReadPosition, (long) readLength, byteBuffer,
                0, this.accessCondition, this.options, this.opContext);

        this.currentBuffer = new ByteArrayInputStream(byteBuffer);
        this.bufferSize = readLength;
        this.bufferStartOffset = this.currentAbsoluteReadPosition;
    }
    catch (final StorageException e) {
        this.streamFaulted = true;
        this.lastError = Utility.initIOException(e);
        throw this.lastError;
    }
}
 
Example #2
Source File: BlobOutputStream.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Waits for at least one task to complete.
 * 
 * @throws IOException
 *             If an I/O error occurs. In particular, an IOException may be thrown if the output stream has been
 *             closed.
 */
private void waitForTaskToComplete() throws IOException {
    boolean completed = false;
    while (this.completionService.poll() != null) {
        completed = true;
    }
    
    if (!completed) {
        try {
            this.completionService.take();
        }
        catch (final InterruptedException e) {
            throw Utility.initIOException(e);
        }
    }
}
 
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: TableBatchOperation.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the table operation at the specified index in the batch operation <code>ArrayList</code>.
 * 
 * @param index
 *            An <code>int</code> which represents the index in the batch operation <code>ArrayList</code> to add
 *            the table operation at.
 * @param element
 *            The {@link TableOperation} to add to the batch operation.
 */
@Override
public void add(final int index, final TableOperation element) {
    Utility.assertNotNull("element", element);

    this.checkSingleQueryPerBatch(element, this.size());

    if (element.getOperationType() == TableOperationType.RETRIEVE) {
        this.lockToPartitionKey(((QueryTableOperation) element).getPartitionKey());
    }
    else {
        this.lockToPartitionKey(element.getEntity().getPartitionKey());
    }

    super.add(index, element);
}
 
Example #5
Source File: NameValidator.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if a blob name is valid.
 * 
 * @param blobName
 *            A String representing the blob name to validate.
 */
public static void validateBlobName(String blobName) {
	if (Utility.isNullOrEmptyOrWhitespace(blobName)) {
		throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.RESOURCE_NAME_EMPTY, SR.BLOB));
	}

	if (blobName.length() < NameValidator.BLOB_FILE_DIRECTORY_MIN_LENGTH || blobName.length() > NameValidator.BLOB_MAX_LENGTH) {
		throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME_LENGTH, SR.BLOB, NameValidator.BLOB_FILE_DIRECTORY_MIN_LENGTH, NameValidator.BLOB_MAX_LENGTH));
	}
	
	int slashCount =  0;
	for (int i = 0; i < blobName.length(); i++)
	{
		if (blobName.charAt(i) == '/')
		{
			slashCount++;
		}
	}
	
	if (slashCount >= 254)
	{
		throw new IllegalArgumentException(SR.TOO_MANY_PATH_SEGMENTS);
	}
}
 
Example #6
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 #7
Source File: LogRecord.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes a new instance of the LogRecord class using a LogRecordStreamReader to populate.
 * 
 * @param reader
 *            the LogRecordStreamReader to use to populate the LogRecord.
 * @throws IOException
 * @throws ParseException
 * @throws URISyntaxException
 */
protected LogRecord(LogRecordStreamReader reader) throws IOException, ParseException, URISyntaxException {
    LAST_MODIFIED_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
    REQUEST_START_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
    
	Utility.assertNotNull("reader", reader);
    this.versionNumber = reader.readString();
    Utility.assertNotNullOrEmpty("versionNumber", this.versionNumber);

    if (this.versionNumber.equals("1.0")) {
        this.populateVersion1Log(reader);
    }
    else {
        throw new IllegalArgumentException(String.format(SR.LOG_VERSION_UNSUPPORTED, this.versionNumber));
    }
}
 
Example #8
Source File: BlobOutputStream.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Flushes this output stream and forces any buffered output bytes to be written out. If any data remains in the
 * buffer it is committed to the service.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 */
@Override
@DoesServiceRequest
public void flush() throws IOException {
    this.checkStreamState();

    this.dispatchWrite();

    // Waits for all submitted tasks to complete
    Set<Future<Void>> requests = new HashSet<Future<Void>>(this.futureSet);
    for (Future<Void> request : requests) {
        // wait for the future to complete
        try {
            request.get();
        }
        catch (Exception e) {
            throw Utility.initIOException(e);
        }

        // If that task threw an error, fail fast
        this.checkStreamState();
    }
}
 
Example #9
Source File: ServicePropertiesSerializer.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the retention policy to the XMLStreamWriter.
 * 
 * @param xmlw
 *            the XMLStreamWriter to write to.
 * @param val
 *            the nullable Integer indicating if the retention policy is enabled, and how long
 * @throws IOException
 *             if there is an error writing the service properties.
 * @throws IllegalStateException
 *             if there is an error writing the service properties.
 * @throws IllegalArgumentException
 *             if there is an error writing the service properties.
 */
private static void writeRetentionPolicy(final XmlSerializer xmlw, final Integer val)
        throws IllegalArgumentException, IllegalStateException, IOException {
    xmlw.startTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT);

    // Enabled
    Utility.serializeElement(xmlw, Constants.AnalyticsConstants.ENABLED_ELEMENT, val != null ? Constants.TRUE
            : Constants.FALSE);

    if (val != null) {
        // Days
        Utility.serializeElement(xmlw, Constants.AnalyticsConstants.DAYS_ELEMENT, val.toString());
    }

    // End Retention Policy
    xmlw.endTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT);
}
 
Example #10
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 #11
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 #12
Source File: CloudFileDirectory.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
private 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());
    }
}
 
Example #13
Source File: LogRecordStreamReader.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Read a String from the stream.
 * 
 * @return
 *         the String read.
 * @throws IOException
 */
public String readString() throws IOException {
    String temp = this.readField(false /* isQuotedString */);

    if (Utility.isNullOrEmpty(temp)) {
        return null;
    }
    else {
        return temp;
    }
}
 
Example #14
Source File: StorageCredentialsAccountAndKey.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of the <code>StorageCredentialsAccountAndKey</code> class, using the specified storage
 * account name and access key; the specified access key is in the form of a byte array.
 * 
 * @param accountName
 *            A <code>String</code> that represents the name of the storage account.
 * @param key
 *            An array of bytes that represent the account access key.
 */
public StorageCredentialsAccountAndKey(final String accountName, final byte[] key) {
    if (Utility.isNullOrEmptyOrWhitespace(accountName)) {
        throw new IllegalArgumentException(SR.INVALID_ACCOUNT_NAME);
    }

    if (key == null || key.length == 0) {
        throw new IllegalArgumentException(SR.INVALID_KEY);
    }

    this.accountName = accountName;
    this.key = key;
}
 
Example #15
Source File: CloudQueueMessage.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the content of the message as a <code>byte</code> array.
 * 
 * @param content
 *        A <code>byte</code> array which contains the content of the message.
 */
public final void setMessageContent(final byte[] content) {
    Utility.assertNotNull("content", content);

    this.messageContent = Base64.encode(content);
    this.messageType = QueueMessageType.BASE_64_ENCODED;
}
 
Example #16
Source File: NameValidator.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if a file name is valid.
 * 
 * @param fileName
 *            A String representing the file name to validate.
 */
public static void validateFileName(String fileName) {
	NameValidator.ValidateFileDirectoryHelper(fileName, SR.FILE);

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

	for (String s : NameValidator.RESERVED_FILE_NAMES) {
		if (s.equalsIgnoreCase(fileName)) {
			throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_RESERVED_NAME, SR.FILE));
		}
	}
}
 
Example #17
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 #18
Source File: AccessCondition.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * RESERVED FOR INTERNAL USE. Verifies the condition is satisfied.
 * 
 * @param etag
 *            A <code>String</code> that represents the ETag to check.
 * @param lastModified
 *            A <code>java.util.Date</code> object that represents the last modified date/time.
 * 
 * @return <code>true</code> if the condition is satisfied; otherwise, <code>false</code>.
 * 
 */
public boolean verifyConditional(final String etag, final Date lastModified) {
    if (this.ifModifiedSinceDate != null) {
        // The IfModifiedSince has a special helper in HttpURLConnection, use it instead of manually setting the
        // header.
        if (!lastModified.after(this.ifModifiedSinceDate)) {
            return false;
        }
    }

    if (this.ifUnmodifiedSinceDate != null) {
        if (lastModified.after(this.ifUnmodifiedSinceDate)) {
            return false;
        }
    }
    
    if (!Utility.isNullOrEmpty(this.ifMatchETag)) {
        if (!this.ifMatchETag.equals(etag) && !this.ifMatchETag.equals("*")) {
            return false;
        }
    }
    
    if (!Utility.isNullOrEmpty(this.ifNoneMatchETag)) {
        if (this.ifNoneMatchETag.equals(etag)) {
            return false;
        }
    }
    
    return true;
}
 
Example #19
Source File: CloudBlobContainer.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a reference to a {@link CloudBlobDirectory} object that represents a virtual blob directory within this
 * container.
 * 
 * @param directoryName
 *            A <code>String</code> that represents the name of the virtual blob directory. If the root directory
 *            (the directory representing the container itself) is desired, use an empty string.
 * @return A {@link CloudBlobDirectory} that represents a virtual blob directory within this container.
 * @throws URISyntaxException
 *             If the resource URI is invalid.
 */
public CloudBlobDirectory getDirectoryReference(String directoryName) throws URISyntaxException {
    Utility.assertNotNull("directoryName", directoryName);

    // if the directory name does not end in the delimiter, add the delimiter
    if (!directoryName.isEmpty() && !directoryName.endsWith(this.blobServiceClient.getDirectoryDelimiter())) {
        directoryName = directoryName.concat(this.blobServiceClient.getDirectoryDelimiter());
    }

    final StorageUri address = PathUtility.appendPathToUri(this.storageUri, directoryName);

    return new CloudBlobDirectory(address, directoryName, this.blobServiceClient, this);
}
 
Example #20
Source File: LogRecordStreamReader.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Read a Date from the stream.
 * 
 * @param format
 *            the format in which the date is stored, for parsing purposes.
 * @return
 *         the Date read.
 * @throws IOException
 * @throws ParseException
 */
public Date readDate(DateFormat format) throws IOException, ParseException {
    String temp = this.readField(false /* isQuotedString */);

    if (Utility.isNullOrEmpty(temp)) {
        return null;
    }
    else {
        return format.parse(temp);
    }
}
 
Example #21
Source File: LogRecordStreamReader.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Read a Long from the stream.
 * 
 * @return
 *         the Long read.
 * @throws IOException
 */
public Long readLong() throws IOException {
    String temp = this.readField(false /* isQuotedString */);

    if (Utility.isNullOrEmpty(temp)) {
        return null;
    }
    else {
        return Long.parseLong(temp);
    }
}
 
Example #22
Source File: LogRecordStreamReader.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Read a URI from the stream.
 * 
 * @return
 *         the URI read.
 * @throws URISyntaxException
 * @throws IOException
 */
public URI readUri() throws URISyntaxException, IOException {
    String temp = this.readField(true /* isQuotedString */);

    if (Utility.isNullOrEmpty(temp)) {
        return null;
    }
    else {
        return new URI(Html.fromHtml(temp).toString());
    }
}
 
Example #23
Source File: TableResult.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
private static Date parseETagForTimestamp(String etag) throws UnsupportedEncodingException {
    // must handle both weak and strong ETags
    if (etag.startsWith("W/")) {
        etag = etag.substring(2);
    }

    // remove etag prefix and '" suffix
    etag = etag.substring(TableConstants.ETAG_PREFIX.length(), etag.length() - 2);

    etag = URLDecoder.decode(etag, Constants.UTF8_CHARSET);

    return Utility.parseDate(etag);
}
 
Example #24
Source File: FileInputStream.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Dispatches a read operation of N bytes.
 * 
 * @param readLength
 *            An <code>int</code> which represents the number of bytes to read.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 */
@DoesServiceRequest
private synchronized void dispatchRead(final int readLength) throws IOException {
    try {
        final byte[] byteBuffer = new byte[readLength];

        this.parentFileRef.downloadRangeInternal(this.currentAbsoluteReadPosition, (long) readLength, byteBuffer,
                0, null /* this.accessCondition */, this.options, this.opContext);

        // Check Etag manually for now -- use access condition once conditional headers supported.
        if (this.accessCondition != null) {
            if (!this.accessCondition.getIfMatch().equals(this.parentFileRef.getProperties().getEtag())) {
                throw new StorageException(StorageErrorCode.CONDITION_FAILED.toString(),
                        SR.INVALID_CONDITIONAL_HEADERS, HttpURLConnection.HTTP_PRECON_FAILED, null, null);
            }
        }

        this.currentBuffer = new ByteArrayInputStream(byteBuffer);
        this.bufferSize = readLength;
        this.bufferStartOffset = this.currentAbsoluteReadPosition;
    }
    catch (final StorageException e) {
        this.streamFaulted = true;
        this.lastError = Utility.initIOException(e);
        throw this.lastError;
    }
}
 
Example #25
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 #26
Source File: PropertyPair.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Reserved for internal use. A utility function that returns <code>true</code> if this property is accessible
 * through reflection.
 * 
 * @return
 */
protected boolean shouldProcess() {
    if (Utility.isNullOrEmpty(this.name) || this.getter == null || this.getter.isAnnotationPresent(Ignore.class)
            || this.setter == null || this.setter.isAnnotationPresent(Ignore.class)
            || (!this.getter.getReturnType().equals(this.setter.getParameterTypes()[0]))) {
        return false;
    }

    return true;
}
 
Example #27
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 #28
Source File: CloudBlobDirectory.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a reference to a virtual blob directory beneath this directory.
 * 
 * @param directoryName
 *            A <code>String</code> that represents the name of the virtual subdirectory.
 * 
 * @return A <code>CloudBlobDirectory</code> object that represents a virtual blob directory beneath this directory.
 * 
 * @throws URISyntaxException
 *             If the resource URI is invalid.
 */
public CloudBlobDirectory getDirectoryReference(String directoryName) throws URISyntaxException {
    Utility.assertNotNullOrEmpty("directoryName", directoryName);

    if (!directoryName.endsWith(this.blobServiceClient.getDirectoryDelimiter())) {
        directoryName = directoryName.concat(this.blobServiceClient.getDirectoryDelimiter());
    }
    final String subDirName = this.getPrefix().concat(directoryName);

    final StorageUri address = PathUtility.appendPathToUri(this.storageUri, directoryName,
            this.blobServiceClient.getDirectoryDelimiter());

    return new CloudBlobDirectory(address, subDirName, this.blobServiceClient, this.container, this);
}
 
Example #29
Source File: PageRangeDiffHandler.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of Page Range Diffs for the given stream.
 * 
 * @return a List of Page Range Diffs for the given stream.
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws IOException
 */
protected static List<PageRangeDiff> getPageRangesDiff(InputStream streamRef) throws ParserConfigurationException,
        SAXException, IOException {
    SAXParser saxParser = Utility.getSAXParser();
    PageRangeDiffHandler handler = new PageRangeDiffHandler();
    saxParser.parse(streamRef, handler);

    return handler.pages;
}
 
Example #30
Source File: BlockListHandler.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a list of {@link BlockEntry} items from the given XML stream.
 * 
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws IOException
 */
public static ArrayList<BlockEntry> getBlockList(InputStream streamRef) throws ParserConfigurationException,
        SAXException, IOException {
    SAXParser saxParser = Utility.getSAXParser();
    BlockListHandler handler = new BlockListHandler();
    saxParser.parse(streamRef, handler);

    return handler.blocks;
}