com.microsoft.azure.storage.StorageException Java Examples

The following examples show how to use com.microsoft.azure.storage.StorageException. 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: TableOperationTests.java    From azure-storage-android with Apache License 2.0 7 votes vote down vote up
@Test
public void testInsertEntityOver1MB() throws StorageException {
    TableRequestOptions options = new TableRequestOptions();
    options.setTablePayloadFormat(TablePayloadFormat.Json);

    Class1 ref = new Class1();
    ref.setA("foo_A");
    ref.setB("foo_B");
    ref.setC("foo_C");
    // 1mb right here
    ref.setD(new byte[1024 * 1024]);
    ref.setPartitionKey("jxscl_odata");
    ref.setRowKey(UUID.randomUUID().toString());

    try {
        this.table.execute(TableOperation.insert(ref), options, null);
        fail();
    } catch (TableServiceException ex) {
        assertEquals(ex.getMessage(), "Bad Request");
        assertTrue(ex.getExtendedErrorInformation().getErrorMessage()
                .startsWith("The entity is larger than the maximum allowed size (1MB)."));
        assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "EntityTooLarge");
    }
}
 
Example #2
Source File: CloudQueueTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testGetMetadata() throws StorageException {
    HashMap<String, String> metadata = new HashMap<String, String>();
    metadata.put("ExistingMetadata", "ExistingMetadataValue");
    this.queue.setMetadata(metadata);
    this.queue.uploadMetadata();
    this.queue.downloadAttributes();
    assertEquals(this.queue.getMetadata().get("ExistingMetadata"), "ExistingMetadataValue");
    assertTrue(this.queue.getMetadata().containsKey("ExistingMetadata"));

    HashMap<String, String> empytMetadata = null;
    this.queue.setMetadata(empytMetadata);
    this.queue.uploadMetadata();
    this.queue.downloadAttributes();
    assertTrue(this.queue.getMetadata().size() == 0);
}
 
Example #3
Source File: TableSerializerTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNulls() throws StorageException {
    TableRequestOptions options = new TableRequestOptions();

    options.setTablePayloadFormat(TablePayloadFormat.JsonFullMetadata);
    testNulls(options, false);

    options.setTablePayloadFormat(TablePayloadFormat.Json);
    testNulls(options, false);

    options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata);
    testNulls(options, false);

    options.setTablePayloadFormat(TablePayloadFormat.JsonNoMetadata);
    testNulls(options, true);
}
 
Example #4
Source File: CloudAppendBlobTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Create a blob and try to download a range of its contents
 */
@Test
public void testAppendBlobDownloadRangeValidationTest()
        throws StorageException, URISyntaxException, IOException {
    final int length = 5 * 1024 * 1024;

    final String appendBlobName = BlobTestHelper
            .generateRandomBlobNameWithPrefix("testBlockBlob");
    final CloudAppendBlob appendBlobRef = this.container
            .getAppendBlobReference(appendBlobName);

    appendBlobRef
            .upload(BlobTestHelper.getRandomDataStream(length), length);

    // Download full blob
    appendBlobRef.download(new ByteArrayOutputStream());
    assertEquals(length, appendBlobRef.getProperties().getLength());

    // Download blob range.
    byte[] downloadBuffer = new byte[100];
    int downloadLength = appendBlobRef.downloadRangeToByteArray(0,
            (long) 100, downloadBuffer, 0);
    assertEquals(length, appendBlobRef.getProperties().getLength());
    assertEquals(100, downloadLength);
}
 
Example #5
Source File: CloudQueue.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the queue if it does not already exist, using the specified request options and operation context.
 * 
 * @param options
 *            A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying
 *            <code>null</code> will use the default request options from the associated service client (
 *            {@link CloudQueueClient}).
 * @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 value of <code>true</code> if the queue is created in the storage service, otherwise <code>false</code>
 *         .
 * 
 * @throws StorageException
 *             If a storage service error occurred during the operation.
 */
@DoesServiceRequest
public boolean createIfNotExists(QueueRequestOptions options, OperationContext opContext) throws StorageException {
    options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);

    boolean exists = this.exists(true, options, opContext);
    if (exists) {
        return false;
    }
    else {
        try {
            this.create(options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
                    && StorageErrorCodeStrings.QUEUE_ALREADY_EXISTS.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
}
 
Example #6
Source File: CloudBlobServerEncryptionTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testBlobEncryption() throws URISyntaxException, StorageException, IOException {
    this.requestFound = false;
    
    OperationContext ctxt = new OperationContext();
    ctxt.getRequestCompletedEventHandler().addListener(new StorageEvent<RequestCompletedEvent>() {
        @Override
        public void eventOccurred(RequestCompletedEvent eventArg) {
            assertTrue(eventArg.getRequestResult().isRequestServiceEncrypted());
            CloudBlobServerEncryptionTests.this.requestFound = true;
        }
    });

    this.blob.uploadText("test", null, null, null, ctxt);
    assertTrue(this.requestFound);
}
 
Example #7
Source File: FileRequest.java    From azure-storage-android with Apache License 2.0 6 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 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
 *            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 <code>HttpURLConnection</code> 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 FileRequestOptions fileOptions,
        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, fileOptions, 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.applyConditionToRequest(request);
    }

    return request;
}
 
Example #8
Source File: CloudQueueTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testUploadMetadataNullInput() throws URISyntaxException, StorageException {
    CloudQueue queueForGet =  this.queue.getServiceClient().getQueueReference(this.queue.getName());

    HashMap<String, String> metadata1 = new HashMap<String, String>();
    String key = "ExistingMetadata1" + UUID.randomUUID().toString().replace("-", "");
    metadata1.put(key, "ExistingMetadataValue1");
    this.queue.setMetadata(metadata1);

    queueForGet.downloadAttributes();
    assertFalse(queueForGet.getMetadata().containsKey(key));

    this.queue.uploadMetadata();
    queueForGet.downloadAttributes();
    assertTrue(queueForGet.getMetadata().containsKey(key));

    this.queue.setMetadata(null);
    this.queue.uploadMetadata();
    queueForGet.downloadAttributes();
    assertTrue(queueForGet.getMetadata().size() == 0);
}
 
Example #9
Source File: AzureStorageService.java    From front50 with Apache License 2.0 6 votes vote down vote up
private void logStorageException(StorageException storageException, String key) {
  String errorMsg = storageException.getExtendedErrorInformation().getErrorMessage();
  String errorCode = storageException.getExtendedErrorInformation().getErrorCode();
  if (key.isEmpty()) {
    log.error(
        "Exception occurred accessing object(s) from storage: HTTPStatusCode {} ErrorCode: {} {}",
        value("responseStatus", storageException.getHttpStatusCode()),
        value("errorCode", errorCode),
        value("errorMsg", errorMsg));
  } else {
    log.error(
        "Exception occurred accessing object(s) from storage: Key {} HTTPStatusCode {} ErrorCode: {} {}",
        value("key", key),
        value("responseStatus", storageException.getHttpStatusCode()),
        value("errorCode", errorCode),
        value("errorMsg", errorMsg));
  }
}
 
Example #10
Source File: QueueTestHelper.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
public static CloudQueue getRandomQueueReference() throws URISyntaxException, StorageException {
    String queueName = generateRandomQueueName();
    CloudQueueClient qClient = createCloudQueueClient();
    CloudQueue queue = qClient.getQueueReference(queueName);

    return queue;
}
 
Example #11
Source File: CloudFileTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Test file resizing.
 * 
 * @throws URISyntaxException
 * @throws StorageException
 */
@Test
public void testCloudFileResize() throws URISyntaxException, StorageException {
    CloudFile file = this.share.getRootDirectoryReference().getFileReference("file1");
    CloudFile file2 = this.share.getRootDirectoryReference().getFileReference("file1");

    file.create(1024);
    assertEquals(1024, file.getProperties().getLength());
    file2.downloadAttributes();
    assertEquals(1024, file2.getProperties().getLength());
    file2.getProperties().setContentType("text/plain");
    file2.uploadProperties();
    file.resize(2048);
    assertEquals(2048, file.getProperties().getLength());
    file.downloadAttributes();
    assertEquals("text/plain", file.getProperties().getContentType());
    file2.downloadAttributes();
    assertEquals(2048, file2.getProperties().getLength());

    // Resize to 0 length
    file.resize(0);
    assertEquals(0, file.getProperties().getLength());
    file.downloadAttributes();
    assertEquals("text/plain", file.getProperties().getContentType());
    file2.downloadAttributes();
    assertEquals(0, file2.getProperties().getLength());
}
 
Example #12
Source File: BlobOutputStream.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Closes this output stream and releases any system resources associated with this stream. If any data remains in
 * the buffer it is committed to the service.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 */
@Override
@DoesServiceRequest
public synchronized void close() throws IOException {
    try {
        // if the user has already closed the stream, this will throw a STREAM_CLOSED exception
        // if an exception was thrown by any thread in the threadExecutor, realize it now
        this.checkStreamState();

        // flush any remaining data
        this.flush();

        // shut down the ExecutorService.
        this.threadExecutor.shutdown();

        // try to commit the blob
        try {
            this.commit();
        }
        catch (final StorageException e) {
            throw Utility.initIOException(e);
        }
    }
    finally {
        // if close() is called again, an exception will be thrown
        this.lastError = new IOException(SR.STREAM_CLOSED);

        // if an exception was thrown and the executor was not yet closed, call shutDownNow() to cancel all tasks 
        // and shutdown the ExecutorService
        if (!this.threadExecutor.isShutdown()) {
            this.threadExecutor.shutdownNow();
        }
    }
}
 
Example #13
Source File: StorageInterfaceImpl.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void startCopyFromBlob(URI source, BlobRequestOptions options,
    OperationContext opContext)
        throws StorageException, URISyntaxException {
  getBlob().startCopyFromBlob(source,
      null, null, options, opContext);
}
 
Example #14
Source File: AzureStorageDeleteRuntimeTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunAtDriverValid() {
    properties.remoteBlobs.include.setValue(Arrays.asList(true));
    properties.remoteBlobs.prefix.setValue(Arrays.asList("block1"));
    ValidationResult validationResult = deleteBlock.initialize(runtimeContainer, properties);
    assertEquals(ValidationResult.OK.getStatus(), validationResult.getStatus());
    deleteBlock.azureStorageBlobService = blobService;
    try {
        final List<CloudBlockBlob> list = new ArrayList<>();
        list.add(new CloudBlockBlob(new URI("https://storagesample.blob.core.windows.net/mycontainer/blob1.txt")));

        when(blobService.listBlobs(anyString(), anyString(), anyBoolean())).thenReturn(new Iterable<ListBlobItem>() {

            @Override
            public Iterator<ListBlobItem> iterator() {
                return new DummyListBlobItemIterator(list);
            }
        });

        when(blobService.deleteBlobBlockIfExist(any(CloudBlockBlob.class))).thenReturn(true);

        deleteBlock.runAtDriver(runtimeContainer);
    } catch (StorageException | URISyntaxException | InvalidKeyException e) {
        fail("should not throw " + e.getMessage());
    }

}
 
Example #15
Source File: TableClientTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
@Category( {CloudTests.class })
public void testGetServiceStats() throws StorageException {
    CloudTableClient tClient = TableTestHelper.createCloudTableClient();
    tClient.getDefaultRequestOptions().setLocationMode(LocationMode.SECONDARY_ONLY);
    TableTestHelper.verifyServiceStats(tClient.getServiceStats());
}
 
Example #16
Source File: AzureStorageClient.java    From azure-kusto-java with MIT License 5 votes vote down vote up
CloudBlockBlob  uploadLocalFileToBlob(String filePath, String blobName, String storageUri, IngestionProperties.DATA_FORMAT dataFormat)
        throws URISyntaxException, StorageException, IOException {
    Ensure.fileExists(filePath);

    CompressionType sourceCompressionType = getCompression(filePath);
    return uploadLocalFileToBlob(filePath, blobName, storageUri, shouldCompress(sourceCompressionType, dataFormat.name()));
}
 
Example #17
Source File: AzureCloudBlobClientActions.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void createCloudBlobContainer(String containerName) {
    CloudBlobContainer cloudBlobContainer = null;

    try {
        int limit = 0;
        do {
            Thread.sleep(6000);
            try {
                cloudBlobContainer = createCloudBlobClient().getContainerReference(containerName);
                if (cloudBlobContainer.createIfNotExists()) {
                    Log.log(LOGGER, format(" Container with Name: %s has been created. ", containerName));
                } else {
                    Log.log(LOGGER, format(" Container with Name: %s already exists. ", containerName));
                }
                limit = 60;
            } catch (StorageException | URISyntaxException createAfterWaitException) {
                limit++;
                if (limit >= 60) {
                    LOGGER.error("Azure Adls Gen2 Blob Storage Container [{}] create cannot be succeed during 360000 ms!\n",
                            containerName, createAfterWaitException);
                }
            }
        } while (limit < 60);
    } catch (InterruptedException waitException) {
        LOGGER.error("Creation of Adls Gen2 Blob Storage Container [{}] has been timed out after 360000 ms!\n", containerName, waitException);
    }
}
 
Example #18
Source File: AzureStorageClient.java    From azure-kusto-java with MIT License 5 votes vote down vote up
void postMessageToQueue(String queuePath, String content) throws StorageException, URISyntaxException {
    // Ensure
    Ensure.stringIsNotBlank(queuePath, "queuePath");
    Ensure.stringIsNotBlank(content, "content");

    CloudQueue queue = new CloudQueue(new URI(queuePath));
    CloudQueueMessage queueMessage = new CloudQueueMessage(content);
    queue.addMessage(queueMessage);
}
 
Example #19
Source File: TableBatchOperationTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
@Category(SecondaryTests.class)
public void testBatchRemoveRange() throws StorageException {
    ArrayList<TableOperation> ops = allOpsList();

    TableBatchOperation batch = new TableBatchOperation();

    batch.addAll(ops);

    batch.removeRange(0, ops.size());
    assertEquals(0, batch.size());

    // should be able to add an entity with a different partition key
    Class1 baseEntity = TableTestHelper.generateRandomEntity("jxscl_odata_2");
    batch.insert(baseEntity);

    batch.removeRange(0, 1);

    batch.addAll(ops);
    batch.removeRange(0, ops.size() - 1);

    // should be not be able to add an entity with a different partition key
    baseEntity = TableTestHelper.generateRandomEntity("jxscl_odata_2");
    try {
        batch.insert(baseEntity);
        fail(SR.OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY);
    }
    catch (IllegalArgumentException e) {
        assertEquals(SR.OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY, e.getMessage());
    }

    batch.removeRange(0, 1);

    // should be able to add a retrieve to the batch
    Class1 ref = TableTestHelper.generateRandomEntity("jxscl_odata");
    TableOperation queryOp = TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ref.getClass());
    batch.add(queryOp);
}
 
Example #20
Source File: CloudFileShareTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Validate share references
 * 
 * @throws StorageException
 * @throws URISyntaxException
 */
@Test
public void testCloudFileShareReference() throws StorageException, URISyntaxException {
    CloudFileClient client = FileTestHelper.createCloudFileClient();
    CloudFileShare share = client.getShareReference("share");

    CloudFileDirectory directory = share.getRootDirectoryReference().getDirectoryReference("directory3");
    CloudFileDirectory directory2 = directory.getDirectoryReference("directory4");

    assertEquals(share.getStorageUri().toString(), directory.getShare().getStorageUri().toString());
    assertEquals(share.getStorageUri().toString(), directory2.getShare().getStorageUri().toString());
    assertEquals(share.getStorageUri().toString(), directory2.getParent().getShare().getStorageUri().toString());
}
 
Example #21
Source File: PutAzureQueueStorage.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final long startNanos = System.nanoTime();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    session.exportTo(flowFile, baos);
    final String flowFileContent = baos.toString();

    CloudQueueMessage message = new CloudQueueMessage(flowFileContent);
    CloudQueueClient cloudQueueClient;
    CloudQueue cloudQueue;

    final int ttl = context.getProperty(TTL).asTimePeriod(TimeUnit.SECONDS).intValue();
    final int delay = context.getProperty(VISIBILITY_DELAY).asTimePeriod(TimeUnit.SECONDS).intValue();
    final String queue = context.getProperty(QUEUE).evaluateAttributeExpressions(flowFile).getValue().toLowerCase();

    try {
        cloudQueueClient = createCloudQueueClient(context, flowFile);
        cloudQueue = cloudQueueClient.getQueueReference(queue);

        final OperationContext operationContext = new OperationContext();
        AzureStorageUtils.setProxy(operationContext, context);

        cloudQueue.addMessage(message, ttl, delay, null, operationContext);
    } catch (URISyntaxException | StorageException e) {
        getLogger().error("Failed to write the message to Azure Queue Storage due to {}", new Object[]{e});
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
    final long transmissionMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
    session.getProvenanceReporter().send(flowFile, cloudQueue.getUri().toString(), transmissionMillis);
}
 
Example #22
Source File: TableEscapingTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnicodeInQuery() throws StorageException {
    doQueryEscapeTest("char中文test");
    doQueryEscapeTest("char中文test");
    doQueryEscapeTest("世界你好");
    doQueryEscapeTest("\u00A9\u770b\u5168\u90e8");
}
 
Example #23
Source File: AzureNativeFileSystemStore.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to Azure storage using account key credentials.
 */
private void connectUsingConnectionStringCredentials(
    final String accountName, final String containerName,
    final String accountKey) throws InvalidKeyException, StorageException,
    IOException, URISyntaxException {
  // If the account name is "acc.blob.core.windows.net", then the
  // rawAccountName is just "acc"
  String rawAccountName = accountName.split("\\.")[0];
  StorageCredentials credentials = new StorageCredentialsAccountAndKey(
      rawAccountName, accountKey);
  connectUsingCredentials(accountName, credentials, containerName);
}
 
Example #24
Source File: CloudQueue.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Get the message request base address (Used internally only).
 * 
 * @return The message request <code>URI</code>.
 * 
 * @throws URISyntaxException
 *             If the resource URI is invalid.
 * @throws StorageException
 */
private StorageUri getMessageRequestAddress(final OperationContext opContext) throws URISyntaxException,
        StorageException {
    if (this.messageRequestAddress == null) {
        this.messageRequestAddress = PathUtility.appendPathToUri(this.getTransformedAddress(opContext),
                QueueConstants.MESSAGES);
    }

    return this.messageRequestAddress;
}
 
Example #25
Source File: CloudPageBlobTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadDownloadFromFile() throws IOException, StorageException, URISyntaxException {
    String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("testblob");
    final CloudPageBlob blob = this.container.getPageBlobReference(blobName);

    this.doUploadDownloadFileTest(blob, 512);
    this.doUploadDownloadFileTest(blob, 4096);
    this.doUploadDownloadFileTest(blob, 5 * 1024 * 1024);
    this.doUploadDownloadFileTest(blob, 11 * 1024 * 1024);
}
 
Example #26
Source File: AzureStorageClientTest.java    From azure-kusto-java with MIT License 5 votes vote down vote up
@BeforeAll
static void setUp() throws StorageException, URISyntaxException {
    testFilePath = Paths.get("src", "test", "resources", "testdata.json").toString();
    testFile = new File(testFilePath);
    testFilePathCompressed = Paths.get("src", "test", "resources", "testdata.json.gz").toString();
    blob = new CloudBlockBlob(new URI("https://ms.com/storageUri"));
}
 
Example #27
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 #28
Source File: CloudFileDirectory.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the directory if it does not exist, using the specified request options and operation context.
 * 
 * @param options
 *            A {@link FileRequestOptions} object that specifies any additional options for the request.
 *            Specifying <code>null</code> will use the default request options from the associated service client
 *            ({@link CloudFileClient}).
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * 
 * @return <code>true</code> if the directory did not already exist and was created; otherwise, <code>false</code>.
 * 
 * @throws StorageException
 *             If a storage service error occurred.
 * @throws URISyntaxException 
 */
@DoesServiceRequest
public boolean createIfNotExists(FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException {
    options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient);

    this.getShare().assertNoSnapshot();

    boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext);
    if (exists) {
        return false;
    }
    else {
        try {
            this.create(options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
                    && StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
}
 
Example #29
Source File: CloudQueueTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testQueueDelete() throws URISyntaxException, StorageException {
    final CloudQueueClient qClient = TestHelper.createCloudQueueClient();
    final String queueName = QueueTestHelper.generateRandomQueueName();
    CloudQueue queue = qClient.getQueueReference(queueName);
    assertEquals(queueName, queue.getName());

    try {
        OperationContext createQueueContext = new OperationContext();
        queue.create(null, createQueueContext);
        assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED);

        OperationContext deleteQueueContext = new OperationContext();
        queue.delete(null, deleteQueueContext);
        assertEquals(deleteQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT);

        try {
            queue.downloadAttributes();
            fail();
        }
        catch (StorageException ex) {
            assertEquals("Expected 404 Exception", ex.getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND);
        }
    }
    finally {
        queue.deleteIfExists();
    }
}
 
Example #30
Source File: CloudQueueTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
@Category({ DevFabricTests.class, DevStoreTests.class })
public void testDeleteQueueIfExists() throws URISyntaxException, StorageException {
    final CloudQueue queue = QueueTestHelper.getRandomQueueReference();

    assertFalse(queue.deleteIfExists());

    try {
        final OperationContext createQueueContext = new OperationContext();
        queue.create(null, createQueueContext);
        assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED);

        assertTrue(queue.deleteIfExists());
        assertFalse(queue.deleteIfExists());

        try {
            queue.create();
            fail("Queue CreateIfNotExists did not throw exception while trying to create a queue in BeingDeleted State");
        }
        catch (StorageException ex) {
            assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex.getHttpStatusCode(),
                    HttpURLConnection.HTTP_CONFLICT);
            assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex.getExtendedErrorInformation()
                    .getErrorCode(), StorageErrorCodeStrings.QUEUE_BEING_DELETED);
        }
    }
    finally {
        queue.delete();
    }
}