Java Code Examples for com.microsoft.azure.storage.blob.CloudBlobContainer#exists()

The following examples show how to use com.microsoft.azure.storage.blob.CloudBlobContainer#exists() . 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: AzureResource.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isFile() {
   try {
      CloudBlobContainer blobContainer = blobClient.getContainerReference(this.container);

      if (blobContainer.exists()) {
         CloudBlockBlob blockBlob = blobContainer.getBlockBlobReference(this.blob);
         return blockBlob.exists();
      }
   }
   catch (Exception e) {
      logger.debug("isFile failed to lookup URI - [{}]", getUri(), e);
   }
   return false;
}
 
Example 2
Source File: AzureResource.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isDirectory() {
   try {
      CloudBlobContainer blobContainer = blobClient.getContainerReference(this.container);

      if (blobContainer.exists()) {
         CloudBlobDirectory blockBlobDir = blobContainer.getDirectoryReference(this.blob);
         // Blob Directories don't exists unless they have something underneath
         return blockBlobDir.listBlobs().iterator().hasNext();
      }
   }
   catch (Exception e) {
      logger.debug("isDirectory failed to lookup URI - [{}]", getUri(), e);
   }
   return false;
}
 
Example 3
Source File: AzureStorageUploader.java    From movie-db-java-on-azure with MIT License 6 votes vote down vote up
private CloudBlobContainer setupContainer(CloudBlobClient blobClient, String containerName) {
    try {
        CloudBlobContainer container = blobClient.getContainerReference(containerName);
        if (!container.exists()) {
            container.createIfNotExists();
            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
            containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
            container.uploadPermissions(containerPermissions);
        }

        return container;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Error setting up container: " + e.getMessage());
        return null;
    }
}
 
Example 4
Source File: AzureFileManager.java    From SEAL-Demo with MIT License 6 votes vote down vote up
/**
 * Delete an existing file from Azure.
 * @param containerName Name of the Azure Blob Container
 * @param destinationName File name
 * @throws URISyntaxException if containerName contains incorrect Uri syntax
 * @throws InvalidKeyException if containerName contains an invalid key
 * @throws StorageException if the blob client is unable to get a container reference
 * @throws ExecutionException if the blob client is unable to get a container reference
 * @throws InterruptedException if the blob client is unable to get a container reference
 */
public static void DeleteFile(String containerName, String destinationName)
        throws URISyntaxException,
               StorageException,
               ExecutionException,
               InterruptedException {
    CloudBlobContainer container = getContainer(containerName);

    if (!container.exists()) {
        throw new IllegalArgumentException("Container does not exist");
    }

    CloudBlockBlob fileBlob = container.getBlockBlobReference(destinationName);
    fileBlob.deleteIfExists();
}
 
Example 5
Source File: AzsValidator.java    From halyard with Apache License 2.0 6 votes vote down vote up
@Override
public void validate(ConfigProblemSetBuilder ps, AzsPersistentStore n) {
  String connectionString =
      "DefaultEndpointsProtocol=https;AccountName="
          + n.getStorageAccountName()
          + ";AccountKey="
          + secretSessionManager.decrypt(n.getStorageAccountKey());

  try {
    CloudStorageAccount storageAccount = CloudStorageAccount.parse(connectionString);

    CloudBlobContainer container =
        storageAccount.createCloudBlobClient().getContainerReference(n.getStorageContainerName());
    container.exists();
  } catch (Exception e) {
    ps.addProblem(
        Problem.Severity.ERROR,
        "Failed to connect to the Azure storage account \""
            + n.getStorageAccountName()
            + "\": "
            + e.getMessage());
    return;
  }
}
 
Example 6
Source File: GenericTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultProxy() throws URISyntaxException, StorageException {
    CloudBlobClient blobClient = TestHelper.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference("container1");

    // Use a default proxy
    OperationContext.setDefaultProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.1.1", 8888)));

    // Turn off retries to make the failure happen faster
    BlobRequestOptions opt = new BlobRequestOptions();
    opt.setRetryPolicyFactory(new RetryNoRetry());

    // Unfortunately HttpURLConnection doesn't expose a getter and the usingProxy method it does have doesn't
    // work as one would expect and will always for us return false. So, we validate by making sure the request
    // fails when we set a bad proxy rather than check the proxy setting itself succeeding.
    try {
        container.exists(null, opt, null);
        fail("Bad proxy should throw an exception.");
    } catch (StorageException e) {
        if (e.getCause().getClass() != ConnectException.class &&
                e.getCause().getClass() != SocketTimeoutException.class &&
                e.getCause().getClass() != SocketException.class) {
            Assert.fail("Unepected exception for bad proxy");
        }
    }
}
 
Example 7
Source File: AzureStorageHelper.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
public static void deleteBlob(final CloudStorageAccount storageAccount, final String containerName,
                              final String blobName) throws Exception {
    final CloudBlobContainer blobContainer = getBlobContainer(storageAccount, containerName);
    if (blobContainer.exists()) {
        final CloudBlockBlob blob = blobContainer.getBlockBlobReference(blobName);
        blob.deleteIfExists();
    }
}
 
Example 8
Source File: GenericTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullRetryPolicy() throws URISyntaxException, StorageException {
    CloudBlobClient blobClient = TestHelper.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference("container1");

    blobClient.getDefaultRequestOptions().setRetryPolicyFactory(null);
    container.exists();
}
 
Example 9
Source File: GenericTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserAgentString() throws URISyntaxException, StorageException {
    // Test with a blob request
    CloudBlobClient blobClient = TestHelper.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference("container1");
    OperationContext sendingRequestEventContext = new OperationContext();
    sendingRequestEventContext.getSendingRequestEventHandler().addListener(new StorageEvent<SendingRequestEvent>() {

        @Override
        public void eventOccurred(SendingRequestEvent eventArg) {
            assertEquals(
                    Constants.HeaderConstants.USER_AGENT_PREFIX
                            + "/"
                            + Constants.HeaderConstants.USER_AGENT_VERSION
                            + " "
                            + String.format(Utility.LOCALE_US, "(Android %s; %s; %s)",
                            android.os.Build.VERSION.RELEASE, android.os.Build.BRAND,
                            android.os.Build.MODEL), ((HttpURLConnection) eventArg.getConnectionObject())
                            .getRequestProperty(Constants.HeaderConstants.USER_AGENT));
        }
    });
    container.exists(null, null, sendingRequestEventContext);

    // Test with a queue request
    CloudQueueClient queueClient = TestHelper.createCloudQueueClient();
    CloudQueue queue = queueClient.getQueueReference("queue1");
    queue.exists(null, sendingRequestEventContext);

    // Test with a table request
    CloudTableClient tableClient = TestHelper.createCloudTableClient();
    CloudTable table = tableClient.getTableReference("table1");
    table.exists(null, sendingRequestEventContext);
}
 
Example 10
Source File: GenericTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testProxyOverridesDefault() throws URISyntaxException, StorageException {
    CloudBlobClient blobClient = TestHelper.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference("container1");

    // Set a default proxy
    OperationContext.setDefaultProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.1.1", 8888)));

    // Turn off retries to make the failure happen faster
    BlobRequestOptions opt = new BlobRequestOptions();
    opt.setRetryPolicyFactory(new RetryNoRetry());

    // Unfortunately HttpURLConnection doesn't expose a getter and the usingProxy method it does have doesn't
    // work as one would expect and will always for us return false. So, we validate by making sure the request
    // fails when we set a bad proxy rather than check the proxy setting itself succeeding.
    try {
        container.exists(null, opt, null);
        fail("Bad proxy should throw an exception.");
    } catch (StorageException e) {
        if (e.getCause().getClass() != ConnectException.class &&
                e.getCause().getClass() != SocketTimeoutException.class) {
            Assert.fail("Unepected exception for bad proxy");
        }
    }

    // Override it with no proxy
    OperationContext opContext = new OperationContext();
    opContext.setProxy(Proxy.NO_PROXY);

    // Should succeed as request-level proxy should override the bad default proxy
    container.exists(null, null, opContext);
}
 
Example 11
Source File: GenericTests.java    From azure-storage-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testProxy() throws URISyntaxException, StorageException {
    CloudBlobClient blobClient = TestHelper.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference("container1");

    // Use a request-level proxy
    OperationContext opContext = new OperationContext();
    opContext.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.1.1", 8888)));

    // Turn of retries to make the failure happen faster
    BlobRequestOptions opt = new BlobRequestOptions();
    opt.setRetryPolicyFactory(new RetryNoRetry());

    // Unfortunately HttpURLConnection doesn't expose a getter and the usingProxy method it does have doesn't
    // work as one would expect and will always for us return false. So, we validate by making sure the request
    // fails when we set a bad proxy rather than check the proxy setting itself.
    try {
        container.exists(null, opt, opContext);
        fail("Bad proxy should throw an exception.");
    } catch (StorageException e) {
        if (e.getCause().getClass() != ConnectException.class &&
                e.getCause().getClass() != SocketTimeoutException.class &&
                e.getCause().getClass() != SocketException.class) {
            Assert.fail("Unepected exception for bad proxy");
        }
    }
}
 
Example 12
Source File: AzureStorageService.java    From crate with Apache License 2.0 4 votes vote down vote up
public boolean doesContainerExist(String container) throws URISyntaxException, StorageException {
    final Tuple<CloudBlobClient, Supplier<OperationContext>> client = client();
    final CloudBlobContainer blobContainer = client.v1().getContainerReference(container);
    return blobContainer.exists(null, null, client.v2().get());
}
 
Example 13
Source File: AzureStorageBlobService.java    From components with Apache License 2.0 4 votes vote down vote up
/**
 * @return true if the a container exist with the given name, false otherwise
 */
public boolean containerExist(final String containerName) throws StorageException, URISyntaxException, InvalidKeyException {
    CloudBlobClient cloudBlobClient = connection.getCloudStorageAccount().createCloudBlobClient();
    CloudBlobContainer cloudBlobContainer = cloudBlobClient.getContainerReference(containerName);
    return cloudBlobContainer.exists(null, null, AzureStorageUtils.getTalendOperationContext());
}
 
Example 14
Source File: AzureBlobStorageTestAccount.java    From big-c with Apache License 2.0 4 votes vote down vote up
public static AzureBlobStorageTestAccount createRoot(final String blobName,
    final int fileSize) throws Exception {

  NativeAzureFileSystem fs = null;
  CloudBlobContainer container = null;
  Configuration conf = createTestConfiguration();

  // Set up a session with the cloud blob client to generate SAS and check the
  // existence of a container and capture the container object.
  CloudStorageAccount account = createTestAccount(conf);
  if (account == null) {
    return null;
  }
  CloudBlobClient blobClient = account.createCloudBlobClient();

  // Capture the account URL and the account name.
  String accountName = conf.get(TEST_ACCOUNT_NAME_PROPERTY_NAME);

  // Set up public container with the specified blob name.
  CloudBlockBlob blobRoot = primeRootContainer(blobClient, accountName,
      blobName, fileSize);

  // Capture the blob container object. It should exist after generating the
  // shared access signature.
  container = blobClient.getContainerReference(AZURE_ROOT_CONTAINER);
  if (null == container || !container.exists()) {
    final String errMsg = String
        .format("Container '%s' expected but not found while creating SAS account.");
    throw new Exception(errMsg);
  }

  // Set the account URI without a container name.
  URI accountUri = createAccountUri(accountName);

  // Initialize the Native Azure file system with anonymous credentials.
  fs = new NativeAzureFileSystem();
  fs.initialize(accountUri, conf);

  // Create test account initializing the appropriate member variables.
  // Set the container value to null for the default root container.
  //
  AzureBlobStorageTestAccount testAcct = new AzureBlobStorageTestAccount(
      fs, account, blobRoot);

  // Return to caller with test account.
  return testAcct;
}
 
Example 15
Source File: AzureBlobStorageTestAccount.java    From big-c with Apache License 2.0 4 votes vote down vote up
public static AzureBlobStorageTestAccount createAnonymous(
    final String blobName, final int fileSize) throws Exception {

  NativeAzureFileSystem fs = null;
  CloudBlobContainer container = null;
  Configuration conf = createTestConfiguration(), noTestAccountConf = new Configuration();

  // Set up a session with the cloud blob client to generate SAS and check the
  // existence of a container and capture the container object.
  CloudStorageAccount account = createTestAccount(conf);
  if (account == null) {
    return null;
  }
  CloudBlobClient blobClient = account.createCloudBlobClient();

  // Capture the account URL and the account name.
  String accountName = conf.get(TEST_ACCOUNT_NAME_PROPERTY_NAME);

  // Generate a container name and create a shared access signature string for
  // it.
  //
  String containerName = generateContainerName();

  // Set up public container with the specified blob name.
  primePublicContainer(blobClient, accountName, containerName, blobName,
      fileSize);

  // Capture the blob container object. It should exist after generating the
  // shared access signature.
  container = blobClient.getContainerReference(containerName);
  if (null == container || !container.exists()) {
    final String errMsg = String
        .format("Container '%s' expected but not found while creating SAS account.");
    throw new Exception(errMsg);
  }

  // Set the account URI.
  URI accountUri = createAccountUri(accountName, containerName);

  // Initialize the Native Azure file system with anonymous credentials.
  fs = new NativeAzureFileSystem();
  fs.initialize(accountUri, noTestAccountConf);

  // Create test account initializing the appropriate member variables.
  AzureBlobStorageTestAccount testAcct = new AzureBlobStorageTestAccount(fs,
      account, container);

  // Return to caller with test account.
  return testAcct;
}
 
Example 16
Source File: AzureBlobStorageTestAccount.java    From hadoop with Apache License 2.0 4 votes vote down vote up
public static AzureBlobStorageTestAccount createRoot(final String blobName,
    final int fileSize) throws Exception {

  NativeAzureFileSystem fs = null;
  CloudBlobContainer container = null;
  Configuration conf = createTestConfiguration();

  // Set up a session with the cloud blob client to generate SAS and check the
  // existence of a container and capture the container object.
  CloudStorageAccount account = createTestAccount(conf);
  if (account == null) {
    return null;
  }
  CloudBlobClient blobClient = account.createCloudBlobClient();

  // Capture the account URL and the account name.
  String accountName = conf.get(TEST_ACCOUNT_NAME_PROPERTY_NAME);

  // Set up public container with the specified blob name.
  CloudBlockBlob blobRoot = primeRootContainer(blobClient, accountName,
      blobName, fileSize);

  // Capture the blob container object. It should exist after generating the
  // shared access signature.
  container = blobClient.getContainerReference(AZURE_ROOT_CONTAINER);
  if (null == container || !container.exists()) {
    final String errMsg = String
        .format("Container '%s' expected but not found while creating SAS account.");
    throw new Exception(errMsg);
  }

  // Set the account URI without a container name.
  URI accountUri = createAccountUri(accountName);

  // Initialize the Native Azure file system with anonymous credentials.
  fs = new NativeAzureFileSystem();
  fs.initialize(accountUri, conf);

  // Create test account initializing the appropriate member variables.
  // Set the container value to null for the default root container.
  //
  AzureBlobStorageTestAccount testAcct = new AzureBlobStorageTestAccount(
      fs, account, blobRoot);

  // Return to caller with test account.
  return testAcct;
}
 
Example 17
Source File: AzureBlobStorageTestAccount.java    From hadoop with Apache License 2.0 4 votes vote down vote up
public static AzureBlobStorageTestAccount createAnonymous(
    final String blobName, final int fileSize) throws Exception {

  NativeAzureFileSystem fs = null;
  CloudBlobContainer container = null;
  Configuration conf = createTestConfiguration(), noTestAccountConf = new Configuration();

  // Set up a session with the cloud blob client to generate SAS and check the
  // existence of a container and capture the container object.
  CloudStorageAccount account = createTestAccount(conf);
  if (account == null) {
    return null;
  }
  CloudBlobClient blobClient = account.createCloudBlobClient();

  // Capture the account URL and the account name.
  String accountName = conf.get(TEST_ACCOUNT_NAME_PROPERTY_NAME);

  // Generate a container name and create a shared access signature string for
  // it.
  //
  String containerName = generateContainerName();

  // Set up public container with the specified blob name.
  primePublicContainer(blobClient, accountName, containerName, blobName,
      fileSize);

  // Capture the blob container object. It should exist after generating the
  // shared access signature.
  container = blobClient.getContainerReference(containerName);
  if (null == container || !container.exists()) {
    final String errMsg = String
        .format("Container '%s' expected but not found while creating SAS account.");
    throw new Exception(errMsg);
  }

  // Set the account URI.
  URI accountUri = createAccountUri(accountName, containerName);

  // Initialize the Native Azure file system with anonymous credentials.
  fs = new NativeAzureFileSystem();
  fs.initialize(accountUri, noTestAccountConf);

  // Create test account initializing the appropriate member variables.
  AzureBlobStorageTestAccount testAcct = new AzureBlobStorageTestAccount(fs,
      account, container);

  // Return to caller with test account.
  return testAcct;
}