com.microsoft.azure.storage.Constants Java Examples

The following examples show how to use com.microsoft.azure.storage.Constants. 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: BlobRequest.java    From azure-storage-android with Apache License 2.0 8 votes vote down vote up
/**
 * Generates a web request to abort a copy operation.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param blobOptions
 *            A {@link BlobRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@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.
 * @param accessCondition
 *            The access condition to apply to the request. Only lease conditions are supported for this operation.
 * @param copyId
 *            A <code>String</code> object that identifying the copy operation.
 * @return a HttpURLConnection configured for the operation.
 * @throws StorageException
 *             an exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 * @throws IOException
 * @throws URISyntaxException
 */
public static HttpURLConnection abortCopy(final URI uri, final BlobRequestOptions blobOptions,
        final OperationContext opContext, final AccessCondition accessCondition, final String copyId)
        throws StorageException, IOException, URISyntaxException {

    final UriQueryBuilder builder = new UriQueryBuilder();

    builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.COPY);
    builder.add(Constants.QueryConstants.COPY_ID, copyId);

    final HttpURLConnection request = BaseRequest.createURLConnection(uri, blobOptions, builder, opContext);

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

    request.setRequestProperty(Constants.HeaderConstants.COPY_ACTION_HEADER,
            Constants.HeaderConstants.COPY_ACTION_ABORT);

    if (accessCondition != null) {
        accessCondition.applyLeaseConditionToRequest(request);
    }

    return request;
}
 
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 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 #3
Source File: FileRequest.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a web request to delete the share and all of the directories and files within it. Sign with no length
 * specified.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param fileOptions
 *            A {@link FileRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@link CloudFileClient}.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the share.
 * @return a HttpURLConnection configured for the operation.
 * @throws StorageException
 * @throws IllegalArgumentException
 */
public static HttpURLConnection deleteShare(final URI uri, final FileRequestOptions fileOptions,
        final OperationContext opContext, final AccessCondition accessCondition, String snapshotVersion, DeleteShareSnapshotsOption deleteSnapshotsOption) 
                throws IOException, URISyntaxException, StorageException {
    final UriQueryBuilder shareBuilder = getShareUriQueryBuilder();
    FileRequest.addShareSnapshot(shareBuilder, snapshotVersion);
    HttpURLConnection request = BaseRequest.delete(uri, fileOptions, shareBuilder, opContext);
    if (accessCondition != null) {
        accessCondition.applyConditionToRequest(request);
    }

    switch (deleteSnapshotsOption) {
    case NONE:
        // nop
        break;
    case INCLUDE_SNAPSHOTS:
        request.setRequestProperty(Constants.HeaderConstants.DELETE_SNAPSHOT_HEADER,
                Constants.HeaderConstants.INCLUDE_SNAPSHOTS_VALUE);
        break;
    default:
        break;
    }

    return request;
}
 
Example #4
Source File: FileSasTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiVersion() throws InvalidKeyException, StorageException, URISyntaxException {
    SharedAccessFilePolicy policy = createSharedAccessPolicy(
            EnumSet.of(SharedAccessFilePermissions.READ, SharedAccessFilePermissions.WRITE,
                    SharedAccessFilePermissions.LIST, SharedAccessFilePermissions.DELETE), 300);
    String sas = this.file.generateSharedAccessSignature(policy, null);
    
    // should not be appended before signing
    assertEquals(-1, sas.indexOf(Constants.QueryConstants.API_VERSION));
    
    OperationContext ctx = new OperationContext();
    ctx.getResponseReceivedEventHandler().addListener(new StorageEvent<ResponseReceivedEvent>() {

        @Override
        public void eventOccurred(ResponseReceivedEvent eventArg) {
            // should be appended after signing
            HttpURLConnection conn = (HttpURLConnection) eventArg.getConnectionObject();
            assertTrue(conn.getURL().toString().indexOf(Constants.QueryConstants.API_VERSION) != -1);
        }
    });

    CloudFile sasFile = new CloudFile(new URI(this.file.getUri().toString() + "?" + sas));
    sasFile.uploadMetadata(null, null, ctx);
}
 
Example #5
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the Range Header for Blob Service Operations.
 * 
 * @param request
 *            The request to add the range header to.
 * @param offset
 *            Starting byte of the range.
 * @param count
 *            Number of bytes in the range.
 */
private static void addRange(HttpURLConnection request, Long offset, Long count) {
    if (offset != null) {
        long rangeStart = offset;
        long rangeEnd;
        if (count != null) {
            rangeEnd = offset + count - 1;
            request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, String.format(
                    Utility.LOCALE_US, Constants.HeaderConstants.RANGE_HEADER_FORMAT, rangeStart, rangeEnd));
        }
        else {
            request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, String.format(
                    Utility.LOCALE_US, Constants.HeaderConstants.BEGIN_RANGE_HEADER_FORMAT, rangeStart));
        }
    }
}
 
Example #6
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a web request to return the ACL for this container. Sign with no length specified.
 * 
 * @param uri
 *            The absolute URI to the container.
 * @param timeout
 *            The server timeout interval.
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the container.
 * @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 HttpURLConnection configured for the operation.
 * @throws StorageException
 */
public static HttpURLConnection getAcl(final URI uri, final BlobRequestOptions blobOptions,
        final AccessCondition accessCondition, final OperationContext opContext) throws IOException,
        URISyntaxException, StorageException {
    final UriQueryBuilder builder = getContainerUriQueryBuilder();
    builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.ACL);

    final HttpURLConnection request = createURLConnection(uri, builder, blobOptions, opContext);

    request.setRequestMethod(Constants.HTTP_GET);

    if (accessCondition != null) {
        accessCondition.applyLeaseConditionToRequest(request);
    }

    return request;
}
 
Example #7
Source File: StorageCredentialsHelper.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Computes a signature for the specified string using the HMAC-SHA256 algorithm.
 * 
 * @param value
 *            The UTF-8-encoded string to sign.
 * 
 * @return A <code>String</code> that contains the HMAC-SHA256-encoded signature.
 * 
 * @throws InvalidKeyException
 *             If the key is not a valid Base64-encoded string.
 */
public static synchronized String computeHmac256(final StorageCredentials creds, final String value) throws InvalidKeyException {
    if (creds.getClass().equals(StorageCredentialsAccountAndKey.class)) {
        byte[] utf8Bytes = null;
        try {
            utf8Bytes = value.getBytes(Constants.UTF8_CHARSET);
        }
        catch (final UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
        return Base64.encode(((StorageCredentialsAccountAndKey) creds).getHmac256().doFinal(utf8Bytes));
    }
    else {
        return null;
    }
}
 
Example #8
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 #9
Source File: CloudBlobContainer.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: SharedAccessFilePolicy.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Converts this policy's permissions to a string.
 * 
 * @return A <code>String</code> that represents the shared access permissions in the "rcwdl" format,
 *         which is described at {@link #setPermissionsFromString(String)}.
 */
@Override
public String permissionsToString() {
    if (this.permissions == null) {
        return Constants.EMPTY_STRING;
    }

    // The service supports a fixed order => rcwdl
    final StringBuilder builder = new StringBuilder();

    if (this.permissions.contains(SharedAccessFilePermissions.READ)) {
        builder.append("r");
    }

    if (this.permissions.contains(SharedAccessFilePermissions.CREATE)) {
        builder.append("c");
    }

    if (this.permissions.contains(SharedAccessFilePermissions.WRITE)) {
        builder.append("w");
    }

    if (this.permissions.contains(SharedAccessFilePermissions.DELETE)) {
        builder.append("d");
    }

    if (this.permissions.contains(SharedAccessFilePermissions.LIST)) {
        builder.append("l");
    }

    return builder.toString();
}
 
Example #11
Source File: BlobOutputStreamTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
public void testWritesConcurrency() throws URISyntaxException, StorageException, IOException {
    int writes = 10;
    
    BlobRequestOptions options = new BlobRequestOptions();
    options.setConcurrentRequestCount(5); 
    
    this.smallPutThresholdHelper(Constants.MB, writes, options);
    this.writeFlushHelper(512, writes, options, 1);
    this.writeFlushHelper(512, writes, options, 4);
    this.writeFlushHelper(512, writes, options, writes+1);
}
 
Example #12
Source File: PageRangeHandler.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    String currentNode = this.elementStack.pop();

    // if the node popped from the stack and the localName don't match, the xml document is improperly formatted
    if (!localName.equals(currentNode)) {
        throw new SAXException(SR.INVALID_RESPONSE_RECEIVED);
    }

    String value = this.bld.toString();
    if (value.isEmpty()) {
        value = null;
    }

    if (BlobConstants.PAGE_RANGE_ELEMENT.equals(currentNode)) {
        final PageRange pageRef = new PageRange(this.startOffset, this.endOffset);
        this.pages.add(pageRef);
    }
    else if (BlobConstants.START_ELEMENT.equals(currentNode)) {
        this.startOffset = Long.parseLong(value);
    }
    else if (Constants.END_ELEMENT.equals(currentNode)) {
        this.endOffset = Long.parseLong(value);
    }

    this.bld = new StringBuilder();
}
 
Example #13
Source File: BlockEntryListSerializer.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a Block List and returns the corresponding UTF8 bytes.
 * 
 * @param blockList
 *            the Iterable of BlockEntry to write
 * @param opContext
 *            a tracking object for the request
 * @return a byte array of the UTF8 bytes representing the serialized block list.
 * @throws IOException
 *             if there is an error writing the block list.
 * @throws IllegalStateException
 *             if there is an error writing the block list.
 * @throws IllegalArgumentException
 *             if there is an error writing the block list.
 */
public static byte[] writeBlockListToStream(final Iterable<BlockEntry> blockList, final OperationContext opContext)
        throws IllegalArgumentException, IllegalStateException, IOException {

    final StringWriter outWriter = new StringWriter();
    final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter);

    // default is UTF8
    xmlw.startDocument(Constants.UTF8_CHARSET, true);
    xmlw.startTag(Constants.EMPTY_STRING, BlobConstants.BLOCK_LIST_ELEMENT);

    for (final BlockEntry block : blockList) {

        if (block.getSearchMode() == BlockSearchMode.COMMITTED) {
            Utility.serializeElement(xmlw, BlobConstants.COMMITTED_ELEMENT, block.getId());
        }
        else if (block.getSearchMode() == BlockSearchMode.UNCOMMITTED) {
            Utility.serializeElement(xmlw, BlobConstants.UNCOMMITTED_ELEMENT, block.getId());
        }
        else if (block.getSearchMode() == BlockSearchMode.LATEST) {
            Utility.serializeElement(xmlw, BlobConstants.LATEST_ELEMENT, block.getId());
        }
    }

    // end BlockListElement
    xmlw.endTag(Constants.EMPTY_STRING, BlobConstants.BLOCK_LIST_ELEMENT);

    // end doc
    xmlw.endDocument();

    return outWriter.toString().getBytes(Constants.UTF8_CHARSET);
}
 
Example #14
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 #15
Source File: BlobResponse.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the LeaseState
 *
 * @param request
 *            The response from server.
 * @return The LeaseState.
 */
public static LeaseState getLeaseState(final HttpURLConnection request) {
    final String leaseState = request.getHeaderField(Constants.HeaderConstants.LEASE_STATE);
    if (!Utility.isNullOrEmpty(leaseState)) {
        return LeaseState.parse(leaseState);
    }

    return LeaseState.UNSPECIFIED;
}
 
Example #16
Source File: BlobResponse.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the copyState
 *
 * @param request
 *            The response from server.
 * @return The CopyState.
 * @throws URISyntaxException
 * @throws ParseException
 */
public static CopyState getCopyState(final HttpURLConnection request) throws URISyntaxException, ParseException {
    String copyStatusString = request.getHeaderField(Constants.HeaderConstants.COPY_STATUS);
    if (!Utility.isNullOrEmpty(copyStatusString)) {
        final CopyState copyState = new CopyState();

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

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

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

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

        final String copyDestinationSnapshotString =
                request.getHeaderField(Constants.HeaderConstants.COPY_DESTINATION_SNAPSHOT_ID);
        if (!Utility.isNullOrEmpty(copyDestinationSnapshotString)) {
            copyState.setCopyDestinationSnapshotID(copyDestinationSnapshotString);
        }

        return copyState;
    }
    else {
        return null;
    }
}
 
Example #17
Source File: BlobResponse.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the LeaseDuration
 *
 * @param request
 *            The response from server.
 * @return The LeaseDuration.
 */
public static LeaseDuration getLeaseDuration(final HttpURLConnection request) {
    final String leaseDuration = request.getHeaderField(Constants.HeaderConstants.LEASE_DURATION);
    if (!Utility.isNullOrEmpty(leaseDuration)) {
        return LeaseDuration.parse(leaseDuration);
    }

    return LeaseDuration.UNSPECIFIED;
}
 
Example #18
Source File: CloudFileShare.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 #19
Source File: SharedAccessBlobPolicy.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Converts this policy's permissions to a string.
 * 
 * @return A <code>String</code> that represents the shared access permissions in the "racwdl" format,
 *         which is described at {@link #setPermissionsFromString(String)}.
 */
@Override
public String permissionsToString() {
    if (this.permissions == null) {
        return Constants.EMPTY_STRING;
    }

    // The service supports a fixed order => racwdl
    final StringBuilder builder = new StringBuilder();

    if (this.permissions.contains(SharedAccessBlobPermissions.READ)) {
        builder.append("r");
    }

    if (this.permissions.contains(SharedAccessBlobPermissions.ADD)) {
        builder.append("a");
    }

    if (this.permissions.contains(SharedAccessBlobPermissions.CREATE)) {
        builder.append("c");
    }

    if (this.permissions.contains(SharedAccessBlobPermissions.WRITE)) {
        builder.append("w");
    }

    if (this.permissions.contains(SharedAccessBlobPermissions.DELETE)) {
        builder.append("d");
    }

    if (this.permissions.contains(SharedAccessBlobPermissions.LIST)) {
        builder.append("l");
    }

    return builder.toString();
}
 
Example #20
Source File: SharedAccessQueuePolicy.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Converts this policy's permissions to a string.
 * 
 * @return A <code>String</code> that represents the shared access permissions in the "raup" format, which is
 *         described at {@link SharedAccessQueuePolicy#setPermissionsFromString(String)}.
 */
@Override
public String permissionsToString() {
    if (this.permissions == null) {
        return Constants.EMPTY_STRING;
    }

    // The service supports a fixed order => raup
    final StringBuilder builder = new StringBuilder();

    if (this.permissions.contains(SharedAccessQueuePermissions.READ)) {
        builder.append("r");
    }

    if (this.permissions.contains(SharedAccessQueuePermissions.ADD)) {
        builder.append("a");
    }

    if (this.permissions.contains(SharedAccessQueuePermissions.UPDATE)) {
        builder.append("u");
    }

    if (this.permissions.contains(SharedAccessQueuePermissions.PROCESSMESSAGES)) {
        builder.append("p");
    }

    return builder.toString();
}
 
Example #21
Source File: EntityProperty.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets this {@link EntityProperty} using the serialized <code>Boolean</code> value.
 * 
 * @param value
 *            The <code>Boolean</code> value to set as the {@link EntityProperty} value.
 */
public synchronized final void setValue(final Boolean value) {
    this.edmType = EdmType.BOOLEAN;
    this.type = Boolean.class;
    if (value == null) {
        this.value = null;
    }
    else {
        this.value = value ? Constants.TRUE : Constants.FALSE;
    }
}
 
Example #22
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 #23
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a HttpURLConnection to Acquire,Release,Break, or Renew a blob/container lease. Sign with 0 length.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param blobOptions
 *            A {@link BlobRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@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.
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the blob.
 * @param action
 *            the LeaseAction to perform
 * @param proposedLeaseId
 *            A <code>String</code> that represents the proposed lease ID for the new lease,
 *            or null if no lease ID is proposed.
 * @param breakPeriodInSeconds
 *            Specifies the amount of time to allow the lease to remain, in seconds.
 *            If null, the break period is the remainder of the current lease, or zero for infinite leases.
 * @param visibilityTimeoutInSeconds
 *            Specifies the the span of time for which to acquire the lease, in seconds.
 *            If null, an infinite lease will be acquired. If not null, this must be greater than zero.
 * @return a HttpURLConnection to use to perform the operation.
 * @throws IOException
 *             if there is an error opening the connection
 * @throws URISyntaxException
 *             if the resource URI is invalid
 * @throws StorageException
 *             an exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 */
private static HttpURLConnection lease(final URI uri, final BlobRequestOptions blobOptions,
        final OperationContext opContext, final AccessCondition accessCondition, final LeaseAction action,
        final Integer leaseTimeInSeconds, final String proposedLeaseId, final Integer breakPeriodInSeconds,
        final UriQueryBuilder builder) throws IOException, URISyntaxException, StorageException {
    final HttpURLConnection request = createURLConnection(uri, builder, blobOptions, opContext);

    request.setDoOutput(true);
    request.setRequestMethod(Constants.HTTP_PUT);
    request.setFixedLengthStreamingMode(0);
    request.setRequestProperty(HeaderConstants.LEASE_ACTION_HEADER, action.toString());

    // Lease duration should only be sent for acquire.
    if (action == LeaseAction.ACQUIRE) {
        // Assert lease duration is in bounds
        if (leaseTimeInSeconds != null && leaseTimeInSeconds != -1) {
            Utility.assertInBounds("leaseTimeInSeconds", leaseTimeInSeconds, Constants.LEASE_DURATION_MIN,
                    Constants.LEASE_DURATION_MAX);
        }

        request.setRequestProperty(HeaderConstants.LEASE_DURATION, leaseTimeInSeconds == null ? "-1"
                : leaseTimeInSeconds.toString());
    }

    if (proposedLeaseId != null) {
        request.setRequestProperty(HeaderConstants.PROPOSED_LEASE_ID_HEADER, proposedLeaseId);
    }

    if (breakPeriodInSeconds != null) {
        // Assert lease break period is in bounds
        Utility.assertInBounds("breakPeriodInSeconds", breakPeriodInSeconds, Constants.LEASE_BREAK_PERIOD_MIN,
                Constants.LEASE_BREAK_PERIOD_MAX);
        request.setRequestProperty(HeaderConstants.LEASE_BREAK_PERIOD_HEADER, breakPeriodInSeconds.toString());
    }

    if (accessCondition != null) {
        accessCondition.applyConditionToRequest(request);
    }
    return request;
}
 
Example #24
Source File: BlobListHandler.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    this.elementStack.push(localName);

    if (BlobConstants.BLOB_ELEMENT.equals(localName) || BlobConstants.BLOB_PREFIX_ELEMENT.equals(localName)) {
        this.blobName = Constants.EMPTY_STRING;
        this.snapshotID = null;
        this.properties = new BlobProperties();
        this.metadata = new HashMap<String, String>();
        this.copyState = null;
    }
}
 
Example #25
Source File: Canonicalizer.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a canonicalized string that will be used to construct the signature string
 * for signing a Table service request under the Shared Key authentication scheme.
 * 
 * @param address
 *            the request URI
 * @param accountName
 *            the account name associated with the request
 * @param method
 *            the verb to be used for the HTTP request.
 * @param contentType
 *            the content type of the HTTP request.
 * @param contentLength
 *            the length of the content written to the outputstream in bytes, -1 if unknown
 * @param date
 *            the date/time specification for the HTTP request
 * @param conn
 *            the HttpURLConnection for the operation.
 * @return A canonicalized string.
 * @throws StorageException
 */
protected static String canonicalizeTableHttpRequest(final java.net.URL address, final String accountName,
        final String method, final String contentType, final long contentLength, final String date,
        final HttpURLConnection conn) throws StorageException {
    // The first element should be the Method of the request.
    // I.e. GET, POST, PUT, or HEAD.
    final StringBuilder canonicalizedString = new StringBuilder(ExpectedTableCanonicalizedStringLength);
    canonicalizedString.append(conn.getRequestMethod());

    // The second element should be the MD5 value.
    // This is optional and may be empty.
    final String httpContentMD5Value = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_MD5);
    appendCanonicalizedElement(canonicalizedString, httpContentMD5Value);

    // The third element should be the content type.
    appendCanonicalizedElement(canonicalizedString, contentType);

    // The fourth element should be the request date.
    // See if there's an storage date header.
    // If there's one, then don't use the date header.

    final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE);
    // If x-ms-date header exists, Date should be that value.
    appendCanonicalizedElement(canonicalizedString, dateString.equals(Constants.EMPTY_STRING) ? date : dateString);

    appendCanonicalizedElement(canonicalizedString, getCanonicalizedResourceLite(address, accountName));

    return canonicalizedString.toString();
}
 
Example #26
Source File: ShareListHandler.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
private void getProperties(String currentNode, String value) throws ParseException {
    if (currentNode.equals(Constants.LAST_MODIFIED_ELEMENT)) {
        this.attributes.getProperties().setLastModified(Utility.parseRFC1123DateFromStringInGMT(value));
    }
    else if (currentNode.equals(Constants.ETAG_ELEMENT)) {
        this.attributes.getProperties().setEtag(Utility.formatETag(value));
    }
    else if (currentNode.equals(FileConstants.SHARE_QUOTA_ELEMENT)) {
        this.attributes.getProperties().setShareQuota(Utility.isNullOrEmpty(value) ? null : Integer.parseInt(value));
    }
}
 
Example #27
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 #28
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a HttpURLConnection to delete the blob, Sign with no length specified.
 * 
 * @param uri
 *            A <code>java.net.URI</code> object that specifies the absolute URI.
 * @param blobOptions
 *            A {@link BlobRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@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.
 * @param accessCondition
 *            An {@link AccessCondition} object that represents the access conditions for the blob.
 * @param snapshotVersion
 *            The snapshot version, if the blob is a snapshot.
 * @param deleteSnapshotsOption
 *            A set of options indicating whether to delete only blobs, only snapshots, or both.
 * @return a HttpURLConnection to use to perform the operation.
 * @throws IOException
 *             if there is an error opening the connection
 * @throws URISyntaxException
 *             if the resource URI is invalid
 * @throws StorageException
 *             an exception representing any error which occurred during the operation.
 * @throws IllegalArgumentException
 */
public static HttpURLConnection deleteBlob(final URI uri, final BlobRequestOptions blobOptions,
        final OperationContext opContext, final AccessCondition accessCondition, final String snapshotVersion,
        final DeleteSnapshotsOption deleteSnapshotsOption) throws IOException, URISyntaxException, StorageException {

    if (snapshotVersion != null && deleteSnapshotsOption != DeleteSnapshotsOption.NONE) {
        throw new IllegalArgumentException(String.format(SR.DELETE_SNAPSHOT_NOT_VALID_ERROR,
                "deleteSnapshotsOption", "snapshot"));
    }

    final UriQueryBuilder builder = new UriQueryBuilder();
    BlobRequest.addSnapshot(builder, snapshotVersion);
    final HttpURLConnection request = BaseRequest.delete(uri, blobOptions, builder, opContext);

    if (accessCondition != null) {
        accessCondition.applyConditionToRequest(request);
    }

    switch (deleteSnapshotsOption) {
        case NONE:
            // nop
            break;
        case INCLUDE_SNAPSHOTS:
            request.setRequestProperty(Constants.HeaderConstants.DELETE_SNAPSHOT_HEADER,
                    BlobConstants.INCLUDE_SNAPSHOTS_VALUE);
            break;
        case DELETE_SNAPSHOTS_ONLY:
            request.setRequestProperty(Constants.HeaderConstants.DELETE_SNAPSHOT_HEADER,
                    BlobConstants.SNAPSHOTS_ONLY_VALUE);
            break;
        default:
            break;
    }

    return request;
}
 
Example #29
Source File: BlockListHandler.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    String currentNode = this.elementStack.pop();

    // if the node popped from the stack and the localName don't match, the xml document is improperly formatted
    if (!localName.equals(currentNode)) {
        throw new SAXException(SR.INVALID_RESPONSE_RECEIVED);
    }

    String value = this.bld.toString();
    if (value.isEmpty()) {
        value = null;
    }

    if (BlobConstants.BLOCK_ELEMENT.equals(currentNode)) {
        final BlockEntry newBlock = new BlockEntry(this.blockName, this.searchMode);
        newBlock.setSize(this.blockSize);
        this.blocks.add(newBlock);
    }
    else if (Constants.NAME_ELEMENT.equals(currentNode)) {
        this.blockName = value;
    }
    else if (BlobConstants.SIZE_ELEMENT.equals(currentNode)) {
        this.blockSize = Long.parseLong(value);
    }

    this.bld = new StringBuilder();
}
 
Example #30
Source File: BlobRequest.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the properties.
 * 
 * @param request
 *            The request.
 * @param properties
 *            The properties object.
 */
private static void addProperties(final HttpURLConnection request, BlobProperties properties) {
    BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CACHE_CONTROL_HEADER,
            properties.getCacheControl());
    BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_DISPOSITION_HEADER,
            properties.getContentDisposition());
    BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_ENCODING_HEADER, properties.getContentEncoding());
    BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_LANGUAGE_HEADER, properties.getContentLanguage());
    BaseRequest.addOptionalHeader(request, BlobConstants.BLOB_CONTENT_MD5_HEADER, properties.getContentMD5());
    BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_TYPE_HEADER, properties.getContentType());
}