com.microsoft.azure.storage.blob.CloudBlobClient Java Examples

The following examples show how to use com.microsoft.azure.storage.blob.CloudBlobClient. 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: AzureStorageUploader.java    From movie-db-java-on-azure with MIT License 8 votes vote down vote up
/**
 * Upload image file to Azure storage with specified name.
 *
 * @param file     image file object
 * @param fileName specified file name
 * @return relative path of the created image blob
 */
public String uploadToAzureStorage(ApplicationContext applicationContext, MultipartFile file, String fileName) {
    String uri = null;

    try {
        CloudStorageAccount storageAccount =
                (CloudStorageAccount) applicationContext.getBean("cloudStorageAccount");
        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

        setupContainer(blobClient, this.thumbnailImageContainer);
        CloudBlobContainer originalImageContainer = setupContainer(blobClient, this.originalImageContainer);

        if (originalImageContainer != null) {
            CloudBlockBlob blob = originalImageContainer.getBlockBlobReference(fileName);
            blob.upload(file.getInputStream(), file.getSize());

            uri = blob.getUri().getPath();
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Error uploading image: " + e.getMessage());
    }

    return uri;
}
 
Example #2
Source File: AzureBlobStorageTestAccount.java    From hadoop with Apache License 2.0 7 votes vote down vote up
private static CloudBlockBlob primeRootContainer(CloudBlobClient blobClient,
    String accountName, String blobName, int fileSize) throws Exception {

  // Create a container if it does not exist. The container name
  // must be lower case.
  CloudBlobContainer container = blobClient.getContainerReference("https://"
      + accountName + "/" + "$root");
  container.createIfNotExists();

  // Create a blob output stream.
  CloudBlockBlob blob = container.getBlockBlobReference(blobName);
  BlobOutputStream outputStream = blob.openOutputStream();

  outputStream.write(new byte[fileSize]);
  outputStream.close();

  // Return a reference to the block blob object.
  return blob;
}
 
Example #3
Source File: VideoStorageAzure.java    From arcusplatform with Apache License 2.0 7 votes vote down vote up
@Override
public void delete(String storagePath) throws Exception {
   long startTime = System.nanoTime();
   URI uri = URI.create(storagePath);

   try {
      String accountName = getAccountName(uri);
      CloudBlobClient client = accounts.get(accountName);
      if (client == null) {
         VIDEO_STORAGE_AZURE_BAD_ACCOUNT_NAME.inc();
         throw new Exception("unknown account name: " + accountName);
      }

      CloudBlockBlob blob = new CloudBlockBlob(uri, client);
      blob.deleteIfExists();

      VIDEO_STORAGE_AZURE_DELETE_SUCCESS.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } catch (Exception ex) {
      VIDEO_STORAGE_AZURE_DELETE_FAIL.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
      throw ex;
   }
}
 
Example #4
Source File: AzureConnectionManager.java    From sunbird-lms-service with MIT License 7 votes vote down vote up
/**
 * This method will provide Azure CloudBlobContainer object or in case of error it will provide
 * null;
 *
 * @param containerName String
 * @return CloudBlobContainer or null
 */
public static CloudBlobContainer getContainer(String containerName, boolean isPublicAccess) {

  try {
    CloudBlobClient cloudBlobClient = getBlobClient();
    // Get a reference to a container , The container name must be lower case
    CloudBlobContainer container =
        cloudBlobClient.getContainerReference(containerName.toLowerCase(Locale.ENGLISH));
    // Create the container if it does not exist.
    boolean response = container.createIfNotExists();
    ProjectLogger.log("container creation done if not exist==" + response);
    // Create a permissions object.
    if (isPublicAccess) {
      BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
      // Include public access in the permissions object.
      containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
      // Set the permissions on the container.
      container.uploadPermissions(containerPermissions);
    }
    return container;
  } catch (Exception e) {
    ProjectLogger.log(e.getMessage(), e);
  }
  return null;
}
 
Example #5
Source File: AzureStorageService.java    From crate with Apache License 2.0 7 votes vote down vote up
public void writeBlob(String container, String blobName, InputStream inputStream, long blobSize,
                      boolean failIfAlreadyExists)
    throws URISyntaxException, StorageException, IOException {
    LOGGER.trace(() -> new ParameterizedMessage("writeBlob({}, stream, {})", blobName, blobSize));
    final Tuple<CloudBlobClient, Supplier<OperationContext>> client = client();
    final CloudBlobContainer blobContainer = client.v1().getContainerReference(container);
    final CloudBlockBlob blob = blobContainer.getBlockBlobReference(blobName);
    try {
        final AccessCondition accessCondition =
            failIfAlreadyExists ? AccessCondition.generateIfNotExistsCondition() : AccessCondition.generateEmptyCondition();
        blob.upload(inputStream, blobSize, accessCondition, null, client.v2().get());
    } catch (final StorageException se) {
        if (failIfAlreadyExists && se.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT &&
            StorageErrorCodeStrings.BLOB_ALREADY_EXISTS.equals(se.getErrorCode())) {
            throw new FileAlreadyExistsException(blobName, null, se.getMessage());
        }
        throw se;
    }
    LOGGER.trace(() -> new ParameterizedMessage("writeBlob({}, stream, {}) - done", blobName, blobSize));
}
 
Example #6
Source File: EventHubImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private Observable<Boolean> createContainerIfNotExistsAsync(final StorageAccount storageAccount,
                                                            final String containerName) {
    return getCloudStorageAsync(storageAccount)
            .flatMap(new Func1<CloudStorageAccount, Observable<Boolean>>() {
                @Override
                public Observable<Boolean> call(final CloudStorageAccount cloudStorageAccount) {
                    return Observable.fromCallable(new Callable<Boolean>() {
                        @Override
                        public Boolean call() {
                            CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
                            try {
                                return blobClient.getContainerReference(containerName).createIfNotExists();
                            } catch (StorageException stgException) {
                                throw Exceptions.propagate(stgException);
                            } catch (URISyntaxException syntaxException) {
                                throw Exceptions.propagate(syntaxException);
                            }
                        }
                    }).subscribeOn(SdkContext.getRxScheduler());
                }
            });
}
 
Example #7
Source File: AzureStorageService.java    From crate with Apache License 2.0 6 votes vote down vote up
public Set<String> children(String account, String container, BlobPath path) throws URISyntaxException, StorageException {
    final var blobsBuilder = new HashSet<String>();
    final Tuple<CloudBlobClient, Supplier<OperationContext>> client = client();
    final CloudBlobContainer blobContainer = client.v1().getContainerReference(container);
    final String keyPath = path.buildAsString();
    final EnumSet<BlobListingDetails> enumBlobListingDetails = EnumSet.of(BlobListingDetails.METADATA);

    for (ListBlobItem blobItem : blobContainer.listBlobs(keyPath, false, enumBlobListingDetails, null, client.v2().get())) {
        if (blobItem instanceof CloudBlobDirectory) {
            final URI uri = blobItem.getUri();
            LOGGER.trace(() -> new ParameterizedMessage("blob url [{}]", uri));
            // uri.getPath is of the form /container/keyPath.* and we want to strip off the /container/
            // this requires 1 + container.length() + 1, with each 1 corresponding to one of the /.
            // Lastly, we add the length of keyPath to the offset to strip this container's path.
            final String uriPath = uri.getPath();
            blobsBuilder.add(uriPath.substring(1 + container.length() + 1 + keyPath.length(), uriPath.length() - 1));
        }
    }
    return Set.copyOf(blobsBuilder);
}
 
Example #8
Source File: ServicePropertiesTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
private ServiceProperties callDownloadServiceProperties(ServiceClient client) throws StorageException {
    if (client.getClass().equals(CloudBlobClient.class)) {
        CloudBlobClient blobClient = (CloudBlobClient) client;
        return blobClient.downloadServiceProperties();
    }
    else if (client.getClass().equals(CloudTableClient.class)) {
        CloudTableClient tableClient = (CloudTableClient) client;
        return tableClient.downloadServiceProperties();
    }
    else if (client.getClass().equals(CloudQueueClient.class)) {
        CloudQueueClient queueClient = (CloudQueueClient) client;
        return queueClient.downloadServiceProperties();
    }
    else {
        fail();
    }
    return null;
}
 
Example #9
Source File: BlobContainerProviderOAuth.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public Stream<ContainerFileSystem.ContainerCreator> getContainerCreators() throws IOException {
  try {
    synchronized (this){
      if(tokenProvider.checkAndUpdateToken()) {
        logger.debug("Storage V1 - BlobContainerProviderOAuth - Token is expired or is about to expire, token has been updated");
        CloudBlobClient newClient = new CloudBlobClient(getConnection(),
          new StorageCredentialsToken(getAccount(), tokenProvider.getToken()));
        setCloudBlobClient(newClient);
      }
    }
  } catch(Exception ex) {
    throw new IOException("Unable to update client token: ", ex);
  }
  return super.getContainerCreators();
}
 
Example #10
Source File: StorageAccountTests.java    From azure-storage-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloudStorageAccountClientUriVerify() throws URISyntaxException, StorageException {
    StorageCredentialsAccountAndKey cred = new StorageCredentialsAccountAndKey(ACCOUNT_NAME, ACCOUNT_KEY);
    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, true);

    CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
    CloudBlobContainer container = blobClient.getContainerReference("container1");
    assertEquals(cloudStorageAccount.getBlobEndpoint().toString() + "/container1", container.getUri().toString());

    CloudQueueClient queueClient = cloudStorageAccount.createCloudQueueClient();
    CloudQueue queue = queueClient.getQueueReference("queue1");
    assertEquals(cloudStorageAccount.getQueueEndpoint().toString() + "/queue1", queue.getUri().toString());

    CloudTableClient tableClient = cloudStorageAccount.createCloudTableClient();
    CloudTable table = tableClient.getTableReference("table1");
    assertEquals(cloudStorageAccount.getTableEndpoint().toString() + "/table1", table.getUri().toString());

    CloudFileClient fileClient = cloudStorageAccount.createCloudFileClient();
    CloudFileShare share = fileClient.getShareReference("share1");
    assertEquals(cloudStorageAccount.getFileEndpoint().toString() + "/share1", share.getUri().toString());
}
 
Example #11
Source File: AzureServiceFactoryTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Before
public void addMockRules() {
  CloudStorageAccount cloudStorageAccount = mock(CloudStorageAccount.class);
  CloudBlobClient cloudBlobClient = mock(CloudBlobClient.class);
  CloudBlobContainer cloudBlobContainer = mock(CloudBlobContainer.class);

  ListBlobItem listBlobItem = mock(ListBlobItem.class);
  List<ListBlobItem> lst = new ArrayList<>();
  lst.add(listBlobItem);
  PowerMockito.mockStatic(CloudStorageAccount.class);
  try {
    doReturn(cloudStorageAccount).when(CloudStorageAccount.class, "parse", Mockito.anyString());
    doReturn(cloudBlobClient).when(cloudStorageAccount).createCloudBlobClient();
    doReturn(cloudBlobContainer).when(cloudBlobClient).getContainerReference(Mockito.anyString());
    doReturn(true).when(cloudBlobContainer).exists();
    when(cloudBlobContainer.listBlobs()).thenReturn(lst);
    when(listBlobItem.getUri()).thenReturn(new URI("http://www.google.com"));

  } catch (Exception e) {
    Assert.fail("Could not initalize mocks, underlying reason " + e.getLocalizedMessage());
  }
}
 
Example #12
Source File: ManageWebAppStorageAccountConnection.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private static CloudBlobContainer setUpStorageAccount(String connectionString, String containerName) {
    try {
        CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
        // Create a blob service client
        CloudBlobClient blobClient = account.createCloudBlobClient();
        CloudBlobContainer container = blobClient.getContainerReference(containerName);
        container.createIfNotExists();
        BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
        // Include public access in the permissions object
        containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
        // Set the permissions on the container
        container.uploadPermissions(containerPermissions);
        return container;
    } catch (StorageException | URISyntaxException | InvalidKeyException e) {
        throw new RuntimeException(e);
    }

}
 
Example #13
Source File: ManageLinuxWebAppStorageAccountConnection.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private static CloudBlobContainer setUpStorageAccount(String connectionString, String containerName) {
    try {
        CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
        // Create a blob service client
        CloudBlobClient blobClient = account.createCloudBlobClient();
        CloudBlobContainer container = blobClient.getContainerReference(containerName);
        container.createIfNotExists();
        BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
        // Include public access in the permissions object
        containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
        // Set the permissions on the container
        container.uploadPermissions(containerPermissions);
        return container;
    } catch (StorageException | URISyntaxException | InvalidKeyException e) {
        throw new RuntimeException(e);
    }

}
 
Example #14
Source File: BlobBasics.java    From storage-blob-java-getting-started with MIT License 6 votes vote down vote up
/**
 * Creates and returns a container for the sample application to use.
 *
 * @param blobClient CloudBlobClient object
 * @param containerName Name of the container to create
 * @return The newly created CloudBlobContainer object
 *
 * @throws StorageException
 * @throws RuntimeException
 * @throws IOException
 * @throws URISyntaxException
 * @throws IllegalArgumentException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 */
private static CloudBlobContainer createContainer(CloudBlobClient blobClient, String containerName) throws StorageException, RuntimeException, IOException, InvalidKeyException, IllegalArgumentException, URISyntaxException, IllegalStateException {

    // Create a new container
    CloudBlobContainer container = blobClient.getContainerReference(containerName);
    try {
        if (container.createIfNotExists() == false) {
            throw new IllegalStateException(String.format("Container with name \"%s\" already exists.", containerName));
        }
    }
    catch (StorageException s) {
        if (s.getCause() instanceof java.net.ConnectException) {
            System.out.println("Caught connection exception from the client. If running with the default configuration please make sure you have started the storage emulator.");
        }
        throw s;
    }

    return container;
}
 
Example #15
Source File: AzureSetup.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void validateAdlsGen2FileSystem(SpiFileSystem fileSystem) throws URISyntaxException, InvalidKeyException, StorageException {
    CloudAdlsGen2View cloudFileSystem = (CloudAdlsGen2View) fileSystem.getCloudFileSystems().get(0);
    String accountName = cloudFileSystem.getAccountName();
    String accountKey = cloudFileSystem.getAccountKey();
    String connectionString = "DefaultEndpointsProtocol=https;AccountName="
            + accountName + ";AccountKey=" + accountKey + ";EndpointSuffix=core.windows.net";
    CloudStorageAccount storageAccount = CloudStorageAccount.parse(connectionString);
    CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
    CloudBlobContainer containerReference = blobClient.getContainerReference(TEST_CONTAINER + System.nanoTime());
    try {
        containerReference.createIfNotExists();
        containerReference.delete();
    } catch (StorageException e) {
        if (e.getCause() instanceof UnknownHostException) {
            throw new CloudConnectorException("The provided account does not belong to a valid storage account");
        }
    }
}
 
Example #16
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 #17
Source File: AzureSetup.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void validateWasbFileSystem(SpiFileSystem fileSystem) throws URISyntaxException, InvalidKeyException, StorageException {
    CloudWasbView cloudFileSystem = (CloudWasbView) fileSystem.getCloudFileSystems().get(0);
    String accountName = cloudFileSystem.getAccountName();
    String accountKey = cloudFileSystem.getAccountKey();
    String connectionString = "DefaultEndpointsProtocol=https;AccountName=" + accountName + ";AccountKey=" + accountKey;
    CloudStorageAccount storageAccount = CloudStorageAccount.parse(connectionString);
    CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
    CloudBlobContainer containerReference = blobClient.getContainerReference(TEST_CONTAINER + System.nanoTime());
    try {
        containerReference.createIfNotExists();
        containerReference.delete();
    } catch (StorageException e) {
        if (e.getCause() instanceof UnknownHostException) {
            throw new CloudConnectorException("The provided account does not belong to a valid storage account");
        }
    }
}
 
Example #18
Source File: TestBlobService.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Before
public void testCreateContainer() {
    try {
        // Retrieve storage account from connection-string.
        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

        // Get a reference to a container.
        // The container name must be lower case
        container = blobClient.getContainerReference(containerName);

        // Create the container if it does not exist.
        container.createIfNotExists();
    } catch (Exception e) {
        // Output the stack trace.
        e.printStackTrace();
    }
}
 
Example #19
Source File: VideoStorageAzure.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public VideoStorageAzure(List<StorageCredentials> accounts, String container, long accessDurationInMs, boolean instrumentOs, int bufferOsSize, int fetchIsSize) {
   this.containers = new ArrayList<>();
   this.accounts = new HashMap<>();
   this.accessDurationInMs = accessDurationInMs;
   this.instrumentOs = instrumentOs;
   this.bufferOsSize = bufferOsSize;
   this.fetchIsSize = fetchIsSize;

   for (StorageCredentials account : accounts) {
      try {
         CloudStorageAccount storage = new CloudStorageAccount(account,true);
         this.accounts.put(account.getAccountName(), storage.createCloudBlobClient());

         CloudBlobClient client = storage.createCloudBlobClient();
         this.containers.add(getStorageContainer(client,container));
      } catch (Exception ex) {
         throw new RuntimeException(ex);
      }
   }

   log.info("configured azure storage with {} accounts", accounts.size());
}
 
Example #20
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 #21
Source File: PreviewStorageAzure.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public PreviewStorageAzure(List<StorageCredentials> accounts, String container, ExecutorService executor) {
	this.containers = new ArrayList<>();
	this.accounts = new HashMap<>();
	this.executor = executor;

	for (StorageCredentials account : accounts) {
		try {
			CloudStorageAccount storage = new CloudStorageAccount(account, true);
			this.accounts.put(account.getAccountName(), storage.createCloudBlobClient());

			CloudBlobClient client = storage.createCloudBlobClient();
			this.containers.add(getStorageContainer(client, container));
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	log.info("configured azure storage with {} accounts", accounts.size());
}
 
Example #22
Source File: AzureStorageBlobService.java    From components with Apache License 2.0 5 votes vote down vote up
/**
 * This method delete the container if exist
 */
public boolean deleteContainerIfExist(final String containerName)
        throws StorageException, URISyntaxException, InvalidKeyException {
    CloudBlobClient cloudBlobClient = connection.getCloudStorageAccount().createCloudBlobClient();
    CloudBlobContainer cloudBlobContainer = cloudBlobClient.getContainerReference(containerName);
    return cloudBlobContainer.deleteIfExists(null, null, AzureStorageUtils.getTalendOperationContext());
}
 
Example #23
Source File: AzureStorageSourceOrSink.java    From components with Apache License 2.0 5 votes vote down vote up
@Override
public List<NamedThing> getSchemaNames(RuntimeContainer container) throws IOException {
    List<NamedThing> result = new ArrayList<>();
    try {
        CloudStorageAccount storageAccount = getAzureConnection(container).getCloudStorageAccount();
        CloudBlobClient client = storageAccount.createCloudBlobClient();
        for (CloudBlobContainer c : client.listContainers()) {
            result.add(new SimpleNamedThing(c.getName(), c.getName()));
        }
    } catch (InvalidKeyException | URISyntaxException e) {
        throw new ComponentException(e);
    }
    return result;
}
 
Example #24
Source File: StorageServiceImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@NotNull
public static String listContainers(@NotNull final StorageInputs inputs) throws Exception {
    final CloudBlobClient blobClient = getCloudBlobClient(inputs);
    final List<String> containerList = new ArrayList<>();
    for (final CloudBlobContainer blobItem : blobClient.listContainers()) {
        containerList.add(blobItem.getName());
    }
    return StringUtilities.join(containerList, COMMA);
}
 
Example #25
Source File: StorageServiceImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@NotNull
public static String listBlobs(@NotNull final StorageInputs inputs) throws Exception {
    final CloudBlobClient blobClient = getCloudBlobClient(inputs);
    final CloudBlobContainer container = blobClient.getContainerReference(inputs.getContainerName());
    final List<String> blobList = new ArrayList<>();
    for (final ListBlobItem blobItem : container.listBlobs()) {
        final String path = blobItem.getUri().getPath();
        blobList.add(path.substring(path.lastIndexOf(FORWARD_SLASH) + 1));
    }
    return StringUtilities.join(blobList, COMMA);
}
 
Example #26
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 #27
Source File: StorageServiceImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@NotNull
public static String createContainer(@NotNull final StorageInputs inputs) throws Exception {
    final CloudBlobClient blobClient = getCloudBlobClient(inputs);
    final CloudBlobContainer container = blobClient.getContainerReference(inputs.getContainerName());
    container.create();
    return inputs.getContainerName();
}
 
Example #28
Source File: StorageServiceImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@NotNull
public static String deleteBlob(@NotNull final StorageInputs inputs) throws Exception {
    final CloudBlobClient blobClient = getCloudBlobClient(inputs);
    final CloudBlobContainer container = blobClient.getContainerReference(inputs.getContainerName());
    final CloudBlockBlob blob = container.getBlockBlobReference(inputs.getBlobName());
    blob.delete();
    return inputs.getBlobName();
}
 
Example #29
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 #30
Source File: AzureStorageBlobService.java    From components with Apache License 2.0 5 votes vote down vote up
public void upload(final String containerName, final String blobName, final InputStream sourceStream, final long length)
        throws StorageException, IOException, URISyntaxException, InvalidKeyException {
    CloudBlobClient cloudBlobClient = connection.getCloudStorageAccount().createCloudBlobClient();
    CloudBlobContainer cloudBlobContainer = cloudBlobClient.getContainerReference(containerName);
    CloudBlockBlob blob = cloudBlobContainer.getBlockBlobReference(blobName);
    blob.upload(sourceStream, length, null, null, AzureStorageUtils.getTalendOperationContext());
}