Reputation: 79
I want to use the following method to delete 30 day old blobs. However, it seems that the part of "sourceBlob.getProperties().getLastModified().getTime();" generates an exception. What could be the possible solutions? The exception message shows null only. The Azure Storage type is Storage (general purpose v1)
public static void deleteOldBlobs(String source) {
try {
System.out.println("deleteOldBlobs started");
CloudStorageAccount storageAccount = CloudStorageAccount
.parse(PropertyUtil.getProperty("storageConnectionString"));
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer sourceContainer = blobClient.getContainerReference(source);
long daysBack = 30;
System.out.println(daysBack);
long cutoff = (daysBack * (24 * 60 * 60 * 1000));
for (ListBlobItem blobItem : sourceContainer.listBlobs()) {
String sourceFileName = new File(blobItem.getUri().toString()).getName();
System.out.println(sourceFileName);
CloudBlockBlob sourceBlob = sourceContainer.getBlockBlobReference(sourceFileName);
System.out.println(sourceBlob.getProperties().getLastModified().getTime());
long diff = new Date().getTime()- sourceBlob.getProperties().getLastModified().getTime();
if (diff > cutoff) {
sourceBlob.deleteIfExists();
}
}
System.out.println("deleteOldBlobs ended");
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
}
}
Upvotes: 0
Views: 98
Reputation: 136369
You'll need to call downloadAttributes()
method to populate the properties of the blob.
Your following line of code:
CloudBlockBlob sourceBlob = sourceContainer.getBlockBlobReference(sourceFileName);
is simply creating an instance of CloudBlockBlob
with the properties set with default values. When you call downloadAttributes
method, a network call will be made and blob's attributes will be fetched.
So your code would be:
CloudBlockBlob sourceBlob = sourceContainer.getBlockBlobReference(sourceFileName);
sourceBlob.downloadAttributes();
System.out.println(sourceBlob.getProperties().getLastModified().getTime());
Considering you have already listed the blobs, you can cast your blobItem
as a CloudBlob
and then you should not have to fetch the attributes (which makes a network call and will make the entire process much slower and error prone).
Upvotes: 2