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

The following examples show how to use com.microsoft.azure.storage.blob.CloudBlockBlob#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 7 votes vote down vote up
@Override
public InputStream open() throws IOException {
   try {
      CloudBlobContainer blobContainer = blobClient.getContainerReference(container);
      blobContainer.createIfNotExists();
      CloudBlockBlob blockBlob = blobContainer.getBlockBlobReference(blob);
      if (blockBlob.exists()) {
         return blockBlob.openInputStream();
      }
      else {
         throw new IOException("Blob does not exist: " + container + ", " + blob);
      }
   }
   catch (Exception e) {
      throw new IOException("Unable to initialize blob: " + container + ", " + blob, e);
   }
}
 
Example 2
Source File: AzureStorageRepository.java    From hawkbit-extensions with Eclipse Public License 1.0 7 votes vote down vote up
@Override
public AbstractDbArtifact getArtifactBySha1(final String tenant, final String sha1Hash16) {
    try {
        final CloudBlockBlob blob = getBlob(tenant, sha1Hash16);

        if (blob == null || !blob.exists()) {
            return null;
        }

        LOG.info("Loading Azure Storage blob from container {} and hash {} for tenant {}",
                blob.getContainer().getName(), sha1Hash16, tenant);

        return new AzureStorageArtifact(blob, sha1Hash16,
                new DbArtifactHash(sha1Hash16, convertToBase16(blob.getProperties().getContentMD5()), null),
                blob.getProperties().getLength(), blob.getProperties().getContentType());
    } catch (final URISyntaxException | StorageException e) {
        throw new ArtifactStoreException("Failed to load artifact into Azure storage", e);
    }
}
 
Example 3
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 4
Source File: PreviewStorageAzure.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] read(String id) throws IOException {
	long startTime = System.nanoTime();

	CloudBlobContainer container = getContainer(id);
	try {
		CloudBlockBlob blob = container.getBlockBlobReference(id);
		if (!blob.exists()) return null;
		blob.downloadAttributes();
		int imageSize = (int) blob.getProperties().getLength();
		byte[] image = new byte[imageSize];
		blob.downloadToByteArray(image, 0);
		VIDEO_PREVIEW_AZURE_DOWNLOAD_SUCCESS.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
		return image;
	} catch (Exception e) {
		VIDEO_PREVIEW_AZURE_DOWNLOAD_FAIL.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
		throw new IOException("Failed to read image " + id);
	}
}
 
Example 5
Source File: AzureStorageService.java    From crate with Apache License 2.0 5 votes vote down vote up
public boolean blobExists(String container, String blob) throws URISyntaxException, StorageException {
    // Container name must be lower case.
    final Tuple<CloudBlobClient, Supplier<OperationContext>> client = client();
    final CloudBlobContainer blobContainer = client.v1().getContainerReference(container);
    final CloudBlockBlob azureBlob = blobContainer.getBlockBlobReference(blob);
    return azureBlob.exists(null, null, client.v2().get());
}
 
Example 6
Source File: AzureStorageRepository.java    From hawkbit-extensions with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected AbstractDbArtifact store(final String tenant, final DbArtifactHash base16Hashes, final String contentType,
        final String tempFile) throws IOException {

    final File file = new File(tempFile);

    try {
        final CloudBlockBlob blob = getBlob(tenant, base16Hashes.getSha1());

        final AzureStorageArtifact artifact = new AzureStorageArtifact(blob, base16Hashes.getSha1(), base16Hashes,
                file.length(), contentType);

        LOG.info("Storing file {} with length {} to Azure Storage container {} in directory {}", file.getName(),
                file.length(), properties.getContainerName(), blob.getParent());

        if (blob.exists()) {
            LOG.debug(
                    "Artifact {} for tenant {} already exists on Azure Storage container {}, don't need to upload twice",
                    base16Hashes.getSha1(), tenant, properties.getContainerName());
            return artifact;
        }

        // Creating blob and uploading file to it
        blob.getProperties().setContentType(contentType);

        final OperationContext context = new OperationContext();
        context.setLoggingEnabled(true);
        context.setLogger(AZURE_SDK_LOG);

        final BlobRequestOptions options = new BlobRequestOptions();
        options.setConcurrentRequestCount(properties.getConcurrentRequestCount());

        blob.uploadFromFile(tempFile, null, options, context);

        final String md5Base16 = convertToBase16(blob.getProperties().getContentMD5());

        LOG.debug("Artifact {} stored on Azure Storage container {} with  server side Etag {} and MD5 hash {}",
                base16Hashes.getSha1(), blob.getContainer().getName(), blob.getProperties().getEtag(), md5Base16);

        return artifact;
    } catch (final URISyntaxException | StorageException e) {
        throw new ArtifactStoreException("Failed to store artifact into Azure storage", e);
    }
}
 
Example 7
Source File: FileSasTests.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testFileCopyFromBlobWithSasAndSnapshot()
        throws URISyntaxException, StorageException, InterruptedException, IOException, InvalidKeyException {
    String blobName = BlobTestHelper.generateRandomBlobNameWithPrefix("testblob");
    CloudBlobContainer container = TestHelper.createCloudBlobClient().getContainerReference(BlobTestHelper.generateRandomContainerName());
    container.createIfNotExists();
    CloudBlockBlob source = container.getBlockBlobReference(blobName);
    String data = "String data";
    source.uploadText(data, Constants.UTF8_CHARSET, null, null, null);

    byte[] buffer = BlobTestHelper.getRandomBuffer(512);
    ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
    source.upload(stream, buffer.length);
    source.getMetadata().put("Test", "value");
    source.uploadMetadata();

    SharedAccessFilePolicy policy = createSharedAccessPolicy(
            EnumSet.of(SharedAccessFilePermissions.READ, SharedAccessFilePermissions.WRITE,
                  SharedAccessFilePermissions.LIST, SharedAccessFilePermissions.DELETE), 5000);

    CloudFile copy = this.share.getRootDirectoryReference().getFileReference("copy");
    String sasToken = copy.generateSharedAccessSignature(policy, null);
    CloudFile copySas = new CloudFile(new URI(copy.getUri().toString() + "?" + sasToken));
    
    // Generate account SAS for the source
    // Cannot generate a SAS directly on a snapshot and the SAS for the destination is only for the destination
    SharedAccessAccountPolicy accountPolicy = new SharedAccessAccountPolicy();
    accountPolicy.setPermissions(EnumSet.of(SharedAccessAccountPermissions.READ, SharedAccessAccountPermissions.WRITE));
    accountPolicy.setServices(EnumSet.of(SharedAccessAccountService.BLOB));
    accountPolicy.setResourceTypes(EnumSet.of(SharedAccessAccountResourceType.OBJECT, SharedAccessAccountResourceType.CONTAINER));
    accountPolicy.setSharedAccessExpiryTime(policy.getSharedAccessExpiryTime());
    final CloudBlobClient sasClient = TestHelper.createCloudBlobClient(accountPolicy, false);

    CloudBlockBlob snapshot = (CloudBlockBlob) source.createSnapshot();
    CloudBlockBlob sasBlob = (CloudBlockBlob) sasClient.getContainerReference(container.getName())
            .getBlobReferenceFromServer(snapshot.getName(), snapshot.getSnapshotID(), null, null, null);
    sasBlob.exists();

    String copyId = copySas.startCopy(BlobTestHelper.defiddler(sasBlob));
    FileTestHelper.waitForCopy(copySas);
    
    copySas.downloadAttributes();
    FileProperties prop1 = copySas.getProperties();
    BlobProperties prop2 = sasBlob.getProperties();

    assertEquals(prop1.getCacheControl(), prop2.getCacheControl());
    assertEquals(prop1.getContentEncoding(), prop2.getContentEncoding());
    assertEquals(prop1.getContentDisposition(),
            prop2.getContentDisposition());
    assertEquals(prop1.getContentLanguage(), prop2.getContentLanguage());
    assertEquals(prop1.getContentMD5(), prop2.getContentMD5());
    assertEquals(prop1.getContentType(), prop2.getContentType());

    assertEquals("value", copySas.getMetadata().get("Test"));
    assertEquals(copyId, copySas.getCopyState().getCopyId());

    snapshot.delete();
    source.delete();
    copySas.delete();
    container.delete();
}