seropian commented on code in PR #2409:
URL: https://github.com/apache/jackrabbit-oak/pull/2409#discussion_r2426595468


##########
oak-blob-cloud-azure/src/main/java/org/apache/jackrabbit/oak/blob/cloud/azure/blobstorage/v8/AzureBlobStoreBackendV8.java:
##########
@@ -0,0 +1,1319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.v8;
+
+import static java.lang.Thread.currentThread;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_BUFFERED_STREAM_THRESHOLD;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_LAST_MODIFIED_KEY;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_ALLOWABLE_UPLOAD_URIS;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_BINARY_UPLOAD_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_MULTIPART_UPLOAD_PART_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_SINGLE_PUT_UPLOAD_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BlOB_META_DIR_NAME;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_META_KEY_PREFIX;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MIN_MULTIPART_UPLOAD_PART_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_REF_KEY;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Queue;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import org.apache.jackrabbit.oak.commons.time.Stopwatch;
+
+import com.google.common.base.Strings;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.AbstractIterator;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.microsoft.azure.storage.AccessCondition;
+import com.microsoft.azure.storage.LocationMode;
+import com.microsoft.azure.storage.ResultContinuation;
+import com.microsoft.azure.storage.ResultSegment;
+import com.microsoft.azure.storage.RetryPolicy;
+import com.microsoft.azure.storage.StorageException;
+import com.microsoft.azure.storage.blob.BlobListingDetails;
+import com.microsoft.azure.storage.blob.BlobRequestOptions;
+import com.microsoft.azure.storage.blob.BlockEntry;
+import com.microsoft.azure.storage.blob.BlockListingFilter;
+import com.microsoft.azure.storage.blob.CloudBlob;
+import com.microsoft.azure.storage.blob.CloudBlobContainer;
+import com.microsoft.azure.storage.blob.CloudBlobDirectory;
+import com.microsoft.azure.storage.blob.CloudBlockBlob;
+import com.microsoft.azure.storage.blob.CopyStatus;
+import com.microsoft.azure.storage.blob.ListBlobItem;
+import com.microsoft.azure.storage.blob.SharedAccessBlobHeaders;
+import com.microsoft.azure.storage.blob.SharedAccessBlobPermissions;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.jackrabbit.core.data.DataIdentifier;
+import org.apache.jackrabbit.core.data.DataRecord;
+import org.apache.jackrabbit.core.data.DataStoreException;
+import 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AbstractAzureBlobStoreBackend;
+import org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants;
+import org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.Utils;
+import org.apache.jackrabbit.oak.commons.PropertiesUtil;
+import org.apache.jackrabbit.oak.commons.conditions.Validate;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordDownloadOptions;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUpload;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUploadException;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUploadOptions;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUploadToken;
+import org.apache.jackrabbit.oak.spi.blob.AbstractDataRecord;
+import org.apache.jackrabbit.oak.spi.blob.AbstractSharedBackend;
+import org.apache.jackrabbit.util.Base64;
+import org.jetbrains.annotations.NotNull;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class AzureBlobStoreBackendV8 extends AbstractAzureBlobStoreBackend {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(AzureBlobStoreBackendV8.class);
+    private static final Logger LOG_STREAMS_DOWNLOAD = 
LoggerFactory.getLogger("oak.datastore.download.streams");
+    private static final Logger LOG_STREAMS_UPLOAD = 
LoggerFactory.getLogger("oak.datastore.upload.streams");
+
+    private Properties properties;
+    private AzureBlobContainerProviderV8 azureBlobContainerProvider;
+    private int concurrentRequestCount = 
AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT;
+    private RetryPolicy retryPolicy;
+    private Integer requestTimeout;
+    private int httpDownloadURIExpirySeconds = 0; // disabled by default
+    private int httpUploadURIExpirySeconds = 0; // disabled by default
+    private String uploadDomainOverride = null;
+    private String downloadDomainOverride = null;
+    private boolean createBlobContainer = true;
+    private boolean presignedDownloadURIVerifyExists = true;
+    private boolean enableSecondaryLocation = 
AzureConstants.AZURE_BLOB_ENABLE_SECONDARY_LOCATION_DEFAULT;
+
+    private Cache<String, URI> httpDownloadURICache;
+
+    private byte[] secret;
+
+    public void setProperties(final Properties properties) {
+        this.properties = properties;
+    }
+
+    private final AtomicReference<CloudBlobContainer> azureContainerReference 
= new AtomicReference<>();
+
+    public CloudBlobContainer getAzureContainer() throws DataStoreException {
+        azureContainerReference.compareAndSet(null, 
azureBlobContainerProvider.getBlobContainer(getBlobRequestOptions()));
+        return azureContainerReference.get();
+    }
+
+    @NotNull
+    protected BlobRequestOptions getBlobRequestOptions() {
+        BlobRequestOptions requestOptions = new BlobRequestOptions();
+        if (null != retryPolicy) {
+            requestOptions.setRetryPolicyFactory(retryPolicy);
+        }
+        if (null != requestTimeout) {
+            requestOptions.setTimeoutIntervalInMs(requestTimeout);
+        }
+        requestOptions.setConcurrentRequestCount(concurrentRequestCount);
+        if (enableSecondaryLocation) {
+            
requestOptions.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
+        }
+        return requestOptions;
+    }
+
+    @Override
+    public void init() throws DataStoreException {
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        Stopwatch watch = Stopwatch.createStarted();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+            LOG.debug("Started backend initialization");
+
+            if (null == properties) {
+                try {
+                    properties = Utils.readConfig(UtilsV8.DEFAULT_CONFIG_FILE);
+                }
+                catch (IOException e) {
+                    throw new DataStoreException("Unable to initialize Azure 
Data Store from " + UtilsV8.DEFAULT_CONFIG_FILE, e);
+                }
+            }
+
+            try {
+                UtilsV8.setProxyIfNeeded(properties);
+                createBlobContainer = PropertiesUtil.toBoolean(
+                        
Strings.emptyToNull(properties.getProperty(AzureConstants.AZURE_CREATE_CONTAINER)),
 true);
+                initAzureDSConfig();
+
+                concurrentRequestCount = PropertiesUtil.toInteger(
+                        
properties.getProperty(AzureConstants.AZURE_BLOB_CONCURRENT_REQUESTS_PER_OPERATION),
+                        AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT);
+                if (concurrentRequestCount < 
AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT) {
+                    LOG.warn("Invalid setting [{}] for 
concurrentRequestsPerOperation (too low); resetting to {}",
+                            concurrentRequestCount,
+                             AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT);
+                    concurrentRequestCount = 
AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT;
+                } else if (concurrentRequestCount > 
AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT) {
+                    LOG.warn("Invalid setting [{}] for 
concurrentRequestsPerOperation (too high); resetting to {}",
+                            concurrentRequestCount,
+                             AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT);
+                    concurrentRequestCount = 
AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT;
+                }
+                LOG.info("Using concurrentRequestsPerOperation={}", 
concurrentRequestCount);
+
+                retryPolicy = 
UtilsV8.getRetryPolicy(properties.getProperty(AzureConstants.AZURE_BLOB_MAX_REQUEST_RETRY));
+                if 
(properties.getProperty(AzureConstants.AZURE_BLOB_REQUEST_TIMEOUT) != null) {
+                    requestTimeout = 
PropertiesUtil.toInteger(properties.getProperty(AzureConstants.AZURE_BLOB_REQUEST_TIMEOUT),
 RetryPolicy.DEFAULT_CLIENT_RETRY_COUNT);
+                }
+                presignedDownloadURIVerifyExists = PropertiesUtil.toBoolean(
+                        
Strings.emptyToNull(properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_VERIFY_EXISTS)),
 true);
+
+                enableSecondaryLocation = PropertiesUtil.toBoolean(
+                        
properties.getProperty(AzureConstants.AZURE_BLOB_ENABLE_SECONDARY_LOCATION_NAME),
+                        
AzureConstants.AZURE_BLOB_ENABLE_SECONDARY_LOCATION_DEFAULT
+                );
+
+                CloudBlobContainer azureContainer = getAzureContainer();
+
+                if (createBlobContainer && !azureContainer.exists()) {
+                    azureContainer.create();
+                    LOG.info("New container created. containerName={}", 
getContainerName());
+                } else {
+                    LOG.info("Reusing existing container. containerName={}", 
getContainerName());
+                }
+                LOG.debug("Backend initialized. duration={}", 
watch.elapsed(TimeUnit.MILLISECONDS));
+
+                // settings pertaining to DataRecordAccessProvider 
functionality
+                String putExpiry = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_UPLOAD_URI_EXPIRY_SECONDS);
+                if (null != putExpiry) {
+                    
this.setHttpUploadURIExpirySeconds(Integer.parseInt(putExpiry));
+                }
+                String getExpiry = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_EXPIRY_SECONDS);
+                if (null != getExpiry) {
+                    
this.setHttpDownloadURIExpirySeconds(Integer.parseInt(getExpiry));
+                    String cacheMaxSize = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_CACHE_MAX_SIZE);
+                    if (null != cacheMaxSize) {
+                        
this.setHttpDownloadURICacheSize(Integer.parseInt(cacheMaxSize));
+                    }
+                    else {
+                        this.setHttpDownloadURICacheSize(0); // default
+                    }
+                }
+                uploadDomainOverride = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_UPLOAD_URI_DOMAIN_OVERRIDE,
 null);
+                downloadDomainOverride = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_DOMAIN_OVERRIDE,
 null);
+
+                // Initialize reference key secret
+                boolean createRefSecretOnInit = PropertiesUtil.toBoolean(
+                        
Strings.emptyToNull(properties.getProperty(AzureConstants.AZURE_REF_ON_INIT)), 
true);
+
+                if (createRefSecretOnInit) {
+                    getOrCreateReferenceKey();
+                }
+            }
+            catch (StorageException e) {
+                throw new DataStoreException(e);
+            }
+        }
+        finally {
+            Thread.currentThread().setContextClassLoader(contextClassLoader);
+        }
+    }
+
+    private void initAzureDSConfig() {
+        AzureBlobContainerProviderV8.Builder builder = 
AzureBlobContainerProviderV8.Builder.builder(properties.getProperty(AzureConstants.AZURE_BLOB_CONTAINER_NAME))
+                
.withAzureConnectionString(properties.getProperty(AzureConstants.AZURE_CONNECTION_STRING,
 ""))
+                
.withAccountName(properties.getProperty(AzureConstants.AZURE_STORAGE_ACCOUNT_NAME,
 ""))
+                
.withBlobEndpoint(properties.getProperty(AzureConstants.AZURE_BLOB_ENDPOINT, 
""))
+                .withSasToken(properties.getProperty(AzureConstants.AZURE_SAS, 
""))
+                
.withAccountKey(properties.getProperty(AzureConstants.AZURE_STORAGE_ACCOUNT_KEY,
 ""))
+                
.withTenantId(properties.getProperty(AzureConstants.AZURE_TENANT_ID, ""))
+                
.withClientId(properties.getProperty(AzureConstants.AZURE_CLIENT_ID, ""))
+                
.withClientSecret(properties.getProperty(AzureConstants.AZURE_CLIENT_SECRET, 
""));
+        azureBlobContainerProvider = builder.build();
+    }
+
+    @Override
+    public InputStream read(DataIdentifier identifier) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            Thread.currentThread().setContextClassLoader(
+                    getClass().getClassLoader());
+            CloudBlockBlob blob = 
getAzureContainer().getBlockBlobReference(key);
+            if (!blob.exists()) {
+                throw new DataStoreException(String.format("Trying to read 
missing blob. identifier=%s", key));
+            }
+
+            InputStream is = blob.openInputStream();
+            LOG.debug("Got input stream for blob. identifier={} duration={}", 
key, watch.elapsed(TimeUnit.MILLISECONDS));
+            if (LOG_STREAMS_DOWNLOAD.isDebugEnabled()) {
+                // Log message, with exception so we can get a trace to see 
where the call came from
+                LOG_STREAMS_DOWNLOAD.debug("Binary downloaded from Azure Blob 
Storage - identifier={}", key, new Exception());
+            }
+            return is;
+        }
+        catch (StorageException e) {
+            LOG.info("Error reading blob. identifier={}", key);
+            throw new DataStoreException(String.format("Cannot read blob. 
identifier=%s", key), e);
+        }
+        catch (URISyntaxException e) {
+            LOG.debug("Error reading blob. identifier={}", key);
+            throw new DataStoreException(String.format("Cannot read blob. 
identifier=%s", key), e);
+        } finally {
+            if (contextClassLoader != null) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void write(DataIdentifier identifier, File file) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+        Objects.requireNonNull(file, "file must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            long len = file.length();
+            LOG.debug("Blob write started. identifier={} length={}", key, len);
+            CloudBlockBlob blob = 
getAzureContainer().getBlockBlobReference(key);
+            if (!blob.exists()) {
+                addLastModified(blob);
+
+                BlobRequestOptions options = new BlobRequestOptions();
+                options.setConcurrentRequestCount(concurrentRequestCount);
+                boolean useBufferedStream = len < 
AZURE_BLOB_BUFFERED_STREAM_THRESHOLD;
+              try (InputStream in = useBufferedStream ? new 
BufferedInputStream(new FileInputStream(file)) : new FileInputStream(file)) {
+                blob.upload(in, len, null, options, null);
+                LOG.debug("Blob created. identifier={} length={} duration={} 
buffered={}", key, len, watch.elapsed(TimeUnit.MILLISECONDS), 
useBufferedStream);
+                if (LOG_STREAMS_UPLOAD.isDebugEnabled()) {
+                  // Log message, with exception so we can get a trace to see 
where the call came from
+                  LOG_STREAMS_UPLOAD.debug("Binary uploaded to Azure Blob 
Storage - identifier={}", key, new Exception());
+                }
+              }
+                return;
+            }
+
+            blob.downloadAttributes();
+            if (blob.getProperties().getLength() != len) {
+                throw new DataStoreException("Length Collision. identifier=" + 
key +
+                        " new length=" + len +
+                        " old length=" + blob.getProperties().getLength());
+            }
+
+            LOG.trace("Blob already exists. identifier={} lastModified={}", 
key, getLastModified(blob));
+            addLastModified(blob);
+            blob.uploadMetadata();
+
+            LOG.debug("Blob updated. identifier={} lastModified={} 
duration={}", key,
+                    getLastModified(blob), 
watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        catch (StorageException e) {
+            LOG.info("Error writing blob. identifier={}", key, e);
+            throw new DataStoreException(String.format("Cannot write blob. 
identifier=%s", key), e);
+        }
+        catch (URISyntaxException | IOException e) {
+            LOG.debug("Error writing blob. identifier={}", key, e);
+            throw new DataStoreException(String.format("Cannot write blob. 
identifier=%s", key), e);
+        } finally {
+            if (null != contextClassLoader) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    private static boolean waitForCopy(CloudBlob blob) throws 
StorageException, InterruptedException {
+        boolean continueLoop = true;
+        CopyStatus status = CopyStatus.PENDING;
+        while (continueLoop) {
+            blob.downloadAttributes();
+            status = blob.getCopyState().getStatus();
+            continueLoop = status == CopyStatus.PENDING;
+            // Sleep if retry is needed
+            if (continueLoop) {
+                Thread.sleep(500);
+            }
+        }
+        return status == CopyStatus.SUCCESS;
+    }
+
+    @Override
+    public DataRecord getRecord(DataIdentifier identifier) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            CloudBlockBlob blob = 
getAzureContainer().getBlockBlobReference(key);
+            blob.downloadAttributes();
+            AzureBlobStoreDataRecord record = new AzureBlobStoreDataRecord(
+                    this,
+                    azureBlobContainerProvider,
+                    new DataIdentifier(getIdentifierName(blob.getName())),
+                    getLastModified(blob),
+                    blob.getProperties().getLength());
+            LOG.debug("Data record read for blob. identifier={} duration={} 
record={}",
+                    key, watch.elapsed(TimeUnit.MILLISECONDS), record);
+            return record;
+        }
+        catch (StorageException e) {
+            if (404 == e.getHttpStatusCode()) {
+                LOG.debug("Unable to get record for blob; blob does not exist. 
identifier={}", key);
+            }
+            else {
+                LOG.info("Error getting data record for blob. identifier={}", 
key, e);
+            }
+            throw new DataStoreException(String.format("Cannot retrieve blob. 
identifier=%s", key), e);
+        }
+        catch (URISyntaxException e) {
+            LOG.debug("Error getting data record for blob. identifier={}", 
key, e);
+            throw new DataStoreException(String.format("Cannot retrieve blob. 
identifier=%s", key), e);
+        } finally {
+            if (contextClassLoader != null) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public Iterator<DataIdentifier> getAllIdentifiers() {
+        return new RecordsIterator<>(
+                input -> new 
DataIdentifier(getIdentifierName(input.getName())));
+    }
+
+    @Override
+    public Iterator<DataRecord> getAllRecords() {
+        final AbstractSharedBackend backend = this;
+        return new RecordsIterator<>(
+                input -> new AzureBlobStoreDataRecord(
+                        backend,
+                        azureBlobContainerProvider,
+                        new DataIdentifier(getIdentifierName(input.getName())),
+                        input.getLastModified(),
+                        input.getLength())
+        );
+    }
+
+    @Override
+    public boolean exists(DataIdentifier identifier) throws DataStoreException 
{
+        Stopwatch watch = Stopwatch.createStarted();
+        String key = getKeyName(identifier);
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            boolean exists 
=getAzureContainer().getBlockBlobReference(key).exists();
+            LOG.debug("Blob exists={} identifier={} duration={}", exists, key, 
watch.elapsed(TimeUnit.MILLISECONDS));
+            return exists;
+        }
+        catch (Exception e) {
+            throw new DataStoreException(e);
+        }
+        finally {
+            if (null != contextClassLoader) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void close() {
+        azureBlobContainerProvider.close();
+        LOG.info("AzureBlobBackend closed.");
+    }
+
+    @Override
+    public void deleteRecord(DataIdentifier identifier) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            boolean result = 
getAzureContainer().getBlockBlobReference(key).deleteIfExists();
+            LOG.debug("Blob {}. identifier={} duration={}",
+                    result ? "deleted" : "delete requested, but it does not 
exist (perhaps already deleted)",
+                    key, watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        catch (StorageException e) {
+            LOG.info("Error deleting blob. identifier={}", key, e);
+            throw new DataStoreException(e);
+        }
+        catch (URISyntaxException e) {
+            throw new DataStoreException(e);
+        } finally {
+            if (contextClassLoader != null) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void addMetadataRecord(InputStream input, String name) throws 
DataStoreException {
+        Objects.requireNonNull(input, "input must not be null");
+        Validate.checkArgument(StringUtils.isNotEmpty(name), "name should not 
be empty");
+
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            addMetadataRecordImpl(input, name, -1L);
+            LOG.debug("Metadata record added. metadataName={} duration={}", 
name, watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        finally {
+            if (null != contextClassLoader) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void addMetadataRecord(File input, String name) throws 
DataStoreException {
+        Objects.requireNonNull(input, "input must not be null");
+        Validate.checkArgument(StringUtils.isNotEmpty(name), "name should not 
be empty");
+
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            addMetadataRecordImpl(new FileInputStream(input), name, 
input.length());
+            LOG.debug("Metadata record added. metadataName={} duration={}", 
name, watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        catch (FileNotFoundException e) {
+            throw new DataStoreException(e);

Review Comment:
   fixed



##########
oak-blob-cloud-azure/src/main/java/org/apache/jackrabbit/oak/blob/cloud/azure/blobstorage/v8/AzureBlobStoreBackendV8.java:
##########
@@ -0,0 +1,1319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.v8;
+
+import static java.lang.Thread.currentThread;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_BUFFERED_STREAM_THRESHOLD;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_LAST_MODIFIED_KEY;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_ALLOWABLE_UPLOAD_URIS;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_BINARY_UPLOAD_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_MULTIPART_UPLOAD_PART_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MAX_SINGLE_PUT_UPLOAD_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BlOB_META_DIR_NAME;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_META_KEY_PREFIX;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_MIN_MULTIPART_UPLOAD_PART_SIZE;
+import static 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants.AZURE_BLOB_REF_KEY;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Queue;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+
+import org.apache.jackrabbit.oak.commons.time.Stopwatch;
+
+import com.google.common.base.Strings;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.AbstractIterator;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.microsoft.azure.storage.AccessCondition;
+import com.microsoft.azure.storage.LocationMode;
+import com.microsoft.azure.storage.ResultContinuation;
+import com.microsoft.azure.storage.ResultSegment;
+import com.microsoft.azure.storage.RetryPolicy;
+import com.microsoft.azure.storage.StorageException;
+import com.microsoft.azure.storage.blob.BlobListingDetails;
+import com.microsoft.azure.storage.blob.BlobRequestOptions;
+import com.microsoft.azure.storage.blob.BlockEntry;
+import com.microsoft.azure.storage.blob.BlockListingFilter;
+import com.microsoft.azure.storage.blob.CloudBlob;
+import com.microsoft.azure.storage.blob.CloudBlobContainer;
+import com.microsoft.azure.storage.blob.CloudBlobDirectory;
+import com.microsoft.azure.storage.blob.CloudBlockBlob;
+import com.microsoft.azure.storage.blob.CopyStatus;
+import com.microsoft.azure.storage.blob.ListBlobItem;
+import com.microsoft.azure.storage.blob.SharedAccessBlobHeaders;
+import com.microsoft.azure.storage.blob.SharedAccessBlobPermissions;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.jackrabbit.core.data.DataIdentifier;
+import org.apache.jackrabbit.core.data.DataRecord;
+import org.apache.jackrabbit.core.data.DataStoreException;
+import 
org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AbstractAzureBlobStoreBackend;
+import org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.AzureConstants;
+import org.apache.jackrabbit.oak.blob.cloud.azure.blobstorage.Utils;
+import org.apache.jackrabbit.oak.commons.PropertiesUtil;
+import org.apache.jackrabbit.oak.commons.conditions.Validate;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordDownloadOptions;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUpload;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUploadException;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUploadOptions;
+import 
org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.DataRecordUploadToken;
+import org.apache.jackrabbit.oak.spi.blob.AbstractDataRecord;
+import org.apache.jackrabbit.oak.spi.blob.AbstractSharedBackend;
+import org.apache.jackrabbit.util.Base64;
+import org.jetbrains.annotations.NotNull;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class AzureBlobStoreBackendV8 extends AbstractAzureBlobStoreBackend {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(AzureBlobStoreBackendV8.class);
+    private static final Logger LOG_STREAMS_DOWNLOAD = 
LoggerFactory.getLogger("oak.datastore.download.streams");
+    private static final Logger LOG_STREAMS_UPLOAD = 
LoggerFactory.getLogger("oak.datastore.upload.streams");
+
+    private Properties properties;
+    private AzureBlobContainerProviderV8 azureBlobContainerProvider;
+    private int concurrentRequestCount = 
AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT;
+    private RetryPolicy retryPolicy;
+    private Integer requestTimeout;
+    private int httpDownloadURIExpirySeconds = 0; // disabled by default
+    private int httpUploadURIExpirySeconds = 0; // disabled by default
+    private String uploadDomainOverride = null;
+    private String downloadDomainOverride = null;
+    private boolean createBlobContainer = true;
+    private boolean presignedDownloadURIVerifyExists = true;
+    private boolean enableSecondaryLocation = 
AzureConstants.AZURE_BLOB_ENABLE_SECONDARY_LOCATION_DEFAULT;
+
+    private Cache<String, URI> httpDownloadURICache;
+
+    private byte[] secret;
+
+    public void setProperties(final Properties properties) {
+        this.properties = properties;
+    }
+
+    private final AtomicReference<CloudBlobContainer> azureContainerReference 
= new AtomicReference<>();
+
+    public CloudBlobContainer getAzureContainer() throws DataStoreException {
+        azureContainerReference.compareAndSet(null, 
azureBlobContainerProvider.getBlobContainer(getBlobRequestOptions()));
+        return azureContainerReference.get();
+    }
+
+    @NotNull
+    protected BlobRequestOptions getBlobRequestOptions() {
+        BlobRequestOptions requestOptions = new BlobRequestOptions();
+        if (null != retryPolicy) {
+            requestOptions.setRetryPolicyFactory(retryPolicy);
+        }
+        if (null != requestTimeout) {
+            requestOptions.setTimeoutIntervalInMs(requestTimeout);
+        }
+        requestOptions.setConcurrentRequestCount(concurrentRequestCount);
+        if (enableSecondaryLocation) {
+            
requestOptions.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
+        }
+        return requestOptions;
+    }
+
+    @Override
+    public void init() throws DataStoreException {
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        Stopwatch watch = Stopwatch.createStarted();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+            LOG.debug("Started backend initialization");
+
+            if (null == properties) {
+                try {
+                    properties = Utils.readConfig(UtilsV8.DEFAULT_CONFIG_FILE);
+                }
+                catch (IOException e) {
+                    throw new DataStoreException("Unable to initialize Azure 
Data Store from " + UtilsV8.DEFAULT_CONFIG_FILE, e);
+                }
+            }
+
+            try {
+                UtilsV8.setProxyIfNeeded(properties);
+                createBlobContainer = PropertiesUtil.toBoolean(
+                        
Strings.emptyToNull(properties.getProperty(AzureConstants.AZURE_CREATE_CONTAINER)),
 true);
+                initAzureDSConfig();
+
+                concurrentRequestCount = PropertiesUtil.toInteger(
+                        
properties.getProperty(AzureConstants.AZURE_BLOB_CONCURRENT_REQUESTS_PER_OPERATION),
+                        AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT);
+                if (concurrentRequestCount < 
AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT) {
+                    LOG.warn("Invalid setting [{}] for 
concurrentRequestsPerOperation (too low); resetting to {}",
+                            concurrentRequestCount,
+                             AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT);
+                    concurrentRequestCount = 
AZURE_BLOB_DEFAULT_CONCURRENT_REQUEST_COUNT;
+                } else if (concurrentRequestCount > 
AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT) {
+                    LOG.warn("Invalid setting [{}] for 
concurrentRequestsPerOperation (too high); resetting to {}",
+                            concurrentRequestCount,
+                             AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT);
+                    concurrentRequestCount = 
AZURE_BLOB_MAX_CONCURRENT_REQUEST_COUNT;
+                }
+                LOG.info("Using concurrentRequestsPerOperation={}", 
concurrentRequestCount);
+
+                retryPolicy = 
UtilsV8.getRetryPolicy(properties.getProperty(AzureConstants.AZURE_BLOB_MAX_REQUEST_RETRY));
+                if 
(properties.getProperty(AzureConstants.AZURE_BLOB_REQUEST_TIMEOUT) != null) {
+                    requestTimeout = 
PropertiesUtil.toInteger(properties.getProperty(AzureConstants.AZURE_BLOB_REQUEST_TIMEOUT),
 RetryPolicy.DEFAULT_CLIENT_RETRY_COUNT);
+                }
+                presignedDownloadURIVerifyExists = PropertiesUtil.toBoolean(
+                        
Strings.emptyToNull(properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_VERIFY_EXISTS)),
 true);
+
+                enableSecondaryLocation = PropertiesUtil.toBoolean(
+                        
properties.getProperty(AzureConstants.AZURE_BLOB_ENABLE_SECONDARY_LOCATION_NAME),
+                        
AzureConstants.AZURE_BLOB_ENABLE_SECONDARY_LOCATION_DEFAULT
+                );
+
+                CloudBlobContainer azureContainer = getAzureContainer();
+
+                if (createBlobContainer && !azureContainer.exists()) {
+                    azureContainer.create();
+                    LOG.info("New container created. containerName={}", 
getContainerName());
+                } else {
+                    LOG.info("Reusing existing container. containerName={}", 
getContainerName());
+                }
+                LOG.debug("Backend initialized. duration={}", 
watch.elapsed(TimeUnit.MILLISECONDS));
+
+                // settings pertaining to DataRecordAccessProvider 
functionality
+                String putExpiry = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_UPLOAD_URI_EXPIRY_SECONDS);
+                if (null != putExpiry) {
+                    
this.setHttpUploadURIExpirySeconds(Integer.parseInt(putExpiry));
+                }
+                String getExpiry = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_EXPIRY_SECONDS);
+                if (null != getExpiry) {
+                    
this.setHttpDownloadURIExpirySeconds(Integer.parseInt(getExpiry));
+                    String cacheMaxSize = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_CACHE_MAX_SIZE);
+                    if (null != cacheMaxSize) {
+                        
this.setHttpDownloadURICacheSize(Integer.parseInt(cacheMaxSize));
+                    }
+                    else {
+                        this.setHttpDownloadURICacheSize(0); // default
+                    }
+                }
+                uploadDomainOverride = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_UPLOAD_URI_DOMAIN_OVERRIDE,
 null);
+                downloadDomainOverride = 
properties.getProperty(AzureConstants.PRESIGNED_HTTP_DOWNLOAD_URI_DOMAIN_OVERRIDE,
 null);
+
+                // Initialize reference key secret
+                boolean createRefSecretOnInit = PropertiesUtil.toBoolean(
+                        
Strings.emptyToNull(properties.getProperty(AzureConstants.AZURE_REF_ON_INIT)), 
true);
+
+                if (createRefSecretOnInit) {
+                    getOrCreateReferenceKey();
+                }
+            }
+            catch (StorageException e) {
+                throw new DataStoreException(e);
+            }
+        }
+        finally {
+            Thread.currentThread().setContextClassLoader(contextClassLoader);
+        }
+    }
+
+    private void initAzureDSConfig() {
+        AzureBlobContainerProviderV8.Builder builder = 
AzureBlobContainerProviderV8.Builder.builder(properties.getProperty(AzureConstants.AZURE_BLOB_CONTAINER_NAME))
+                
.withAzureConnectionString(properties.getProperty(AzureConstants.AZURE_CONNECTION_STRING,
 ""))
+                
.withAccountName(properties.getProperty(AzureConstants.AZURE_STORAGE_ACCOUNT_NAME,
 ""))
+                
.withBlobEndpoint(properties.getProperty(AzureConstants.AZURE_BLOB_ENDPOINT, 
""))
+                .withSasToken(properties.getProperty(AzureConstants.AZURE_SAS, 
""))
+                
.withAccountKey(properties.getProperty(AzureConstants.AZURE_STORAGE_ACCOUNT_KEY,
 ""))
+                
.withTenantId(properties.getProperty(AzureConstants.AZURE_TENANT_ID, ""))
+                
.withClientId(properties.getProperty(AzureConstants.AZURE_CLIENT_ID, ""))
+                
.withClientSecret(properties.getProperty(AzureConstants.AZURE_CLIENT_SECRET, 
""));
+        azureBlobContainerProvider = builder.build();
+    }
+
+    @Override
+    public InputStream read(DataIdentifier identifier) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            Thread.currentThread().setContextClassLoader(
+                    getClass().getClassLoader());
+            CloudBlockBlob blob = 
getAzureContainer().getBlockBlobReference(key);
+            if (!blob.exists()) {
+                throw new DataStoreException(String.format("Trying to read 
missing blob. identifier=%s", key));
+            }
+
+            InputStream is = blob.openInputStream();
+            LOG.debug("Got input stream for blob. identifier={} duration={}", 
key, watch.elapsed(TimeUnit.MILLISECONDS));
+            if (LOG_STREAMS_DOWNLOAD.isDebugEnabled()) {
+                // Log message, with exception so we can get a trace to see 
where the call came from
+                LOG_STREAMS_DOWNLOAD.debug("Binary downloaded from Azure Blob 
Storage - identifier={}", key, new Exception());
+            }
+            return is;
+        }
+        catch (StorageException e) {
+            LOG.info("Error reading blob. identifier={}", key);
+            throw new DataStoreException(String.format("Cannot read blob. 
identifier=%s", key), e);
+        }
+        catch (URISyntaxException e) {
+            LOG.debug("Error reading blob. identifier={}", key);
+            throw new DataStoreException(String.format("Cannot read blob. 
identifier=%s", key), e);
+        } finally {
+            if (contextClassLoader != null) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void write(DataIdentifier identifier, File file) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+        Objects.requireNonNull(file, "file must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            long len = file.length();
+            LOG.debug("Blob write started. identifier={} length={}", key, len);
+            CloudBlockBlob blob = 
getAzureContainer().getBlockBlobReference(key);
+            if (!blob.exists()) {
+                addLastModified(blob);
+
+                BlobRequestOptions options = new BlobRequestOptions();
+                options.setConcurrentRequestCount(concurrentRequestCount);
+                boolean useBufferedStream = len < 
AZURE_BLOB_BUFFERED_STREAM_THRESHOLD;
+              try (InputStream in = useBufferedStream ? new 
BufferedInputStream(new FileInputStream(file)) : new FileInputStream(file)) {
+                blob.upload(in, len, null, options, null);
+                LOG.debug("Blob created. identifier={} length={} duration={} 
buffered={}", key, len, watch.elapsed(TimeUnit.MILLISECONDS), 
useBufferedStream);
+                if (LOG_STREAMS_UPLOAD.isDebugEnabled()) {
+                  // Log message, with exception so we can get a trace to see 
where the call came from
+                  LOG_STREAMS_UPLOAD.debug("Binary uploaded to Azure Blob 
Storage - identifier={}", key, new Exception());
+                }
+              }
+                return;
+            }
+
+            blob.downloadAttributes();
+            if (blob.getProperties().getLength() != len) {
+                throw new DataStoreException("Length Collision. identifier=" + 
key +
+                        " new length=" + len +
+                        " old length=" + blob.getProperties().getLength());
+            }
+
+            LOG.trace("Blob already exists. identifier={} lastModified={}", 
key, getLastModified(blob));
+            addLastModified(blob);
+            blob.uploadMetadata();
+
+            LOG.debug("Blob updated. identifier={} lastModified={} 
duration={}", key,
+                    getLastModified(blob), 
watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        catch (StorageException e) {
+            LOG.info("Error writing blob. identifier={}", key, e);
+            throw new DataStoreException(String.format("Cannot write blob. 
identifier=%s", key), e);
+        }
+        catch (URISyntaxException | IOException e) {
+            LOG.debug("Error writing blob. identifier={}", key, e);
+            throw new DataStoreException(String.format("Cannot write blob. 
identifier=%s", key), e);
+        } finally {
+            if (null != contextClassLoader) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    private static boolean waitForCopy(CloudBlob blob) throws 
StorageException, InterruptedException {
+        boolean continueLoop = true;
+        CopyStatus status = CopyStatus.PENDING;
+        while (continueLoop) {
+            blob.downloadAttributes();
+            status = blob.getCopyState().getStatus();
+            continueLoop = status == CopyStatus.PENDING;
+            // Sleep if retry is needed
+            if (continueLoop) {
+                Thread.sleep(500);
+            }
+        }
+        return status == CopyStatus.SUCCESS;
+    }
+
+    @Override
+    public DataRecord getRecord(DataIdentifier identifier) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            CloudBlockBlob blob = 
getAzureContainer().getBlockBlobReference(key);
+            blob.downloadAttributes();
+            AzureBlobStoreDataRecord record = new AzureBlobStoreDataRecord(
+                    this,
+                    azureBlobContainerProvider,
+                    new DataIdentifier(getIdentifierName(blob.getName())),
+                    getLastModified(blob),
+                    blob.getProperties().getLength());
+            LOG.debug("Data record read for blob. identifier={} duration={} 
record={}",
+                    key, watch.elapsed(TimeUnit.MILLISECONDS), record);
+            return record;
+        }
+        catch (StorageException e) {
+            if (404 == e.getHttpStatusCode()) {
+                LOG.debug("Unable to get record for blob; blob does not exist. 
identifier={}", key);
+            }
+            else {
+                LOG.info("Error getting data record for blob. identifier={}", 
key, e);
+            }
+            throw new DataStoreException(String.format("Cannot retrieve blob. 
identifier=%s", key), e);
+        }
+        catch (URISyntaxException e) {
+            LOG.debug("Error getting data record for blob. identifier={}", 
key, e);
+            throw new DataStoreException(String.format("Cannot retrieve blob. 
identifier=%s", key), e);
+        } finally {
+            if (contextClassLoader != null) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public Iterator<DataIdentifier> getAllIdentifiers() {
+        return new RecordsIterator<>(
+                input -> new 
DataIdentifier(getIdentifierName(input.getName())));
+    }
+
+    @Override
+    public Iterator<DataRecord> getAllRecords() {
+        final AbstractSharedBackend backend = this;
+        return new RecordsIterator<>(
+                input -> new AzureBlobStoreDataRecord(
+                        backend,
+                        azureBlobContainerProvider,
+                        new DataIdentifier(getIdentifierName(input.getName())),
+                        input.getLastModified(),
+                        input.getLength())
+        );
+    }
+
+    @Override
+    public boolean exists(DataIdentifier identifier) throws DataStoreException 
{
+        Stopwatch watch = Stopwatch.createStarted();
+        String key = getKeyName(identifier);
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            boolean exists 
=getAzureContainer().getBlockBlobReference(key).exists();
+            LOG.debug("Blob exists={} identifier={} duration={}", exists, key, 
watch.elapsed(TimeUnit.MILLISECONDS));
+            return exists;
+        }
+        catch (Exception e) {
+            throw new DataStoreException(e);
+        }
+        finally {
+            if (null != contextClassLoader) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void close() {
+        azureBlobContainerProvider.close();
+        LOG.info("AzureBlobBackend closed.");
+    }
+
+    @Override
+    public void deleteRecord(DataIdentifier identifier) throws 
DataStoreException {
+        Objects.requireNonNull(identifier, "identifier must not be null");
+
+        String key = getKeyName(identifier);
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            boolean result = 
getAzureContainer().getBlockBlobReference(key).deleteIfExists();
+            LOG.debug("Blob {}. identifier={} duration={}",
+                    result ? "deleted" : "delete requested, but it does not 
exist (perhaps already deleted)",
+                    key, watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        catch (StorageException e) {
+            LOG.info("Error deleting blob. identifier={}", key, e);
+            throw new DataStoreException(e);
+        }
+        catch (URISyntaxException e) {
+            throw new DataStoreException(e);
+        } finally {
+            if (contextClassLoader != null) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void addMetadataRecord(InputStream input, String name) throws 
DataStoreException {
+        Objects.requireNonNull(input, "input must not be null");
+        Validate.checkArgument(StringUtils.isNotEmpty(name), "name should not 
be empty");
+
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            addMetadataRecordImpl(input, name, -1L);
+            LOG.debug("Metadata record added. metadataName={} duration={}", 
name, watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        finally {
+            if (null != contextClassLoader) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    @Override
+    public void addMetadataRecord(File input, String name) throws 
DataStoreException {
+        Objects.requireNonNull(input, "input must not be null");
+        Validate.checkArgument(StringUtils.isNotEmpty(name), "name should not 
be empty");
+
+        Stopwatch watch = Stopwatch.createStarted();
+        ClassLoader contextClassLoader = 
Thread.currentThread().getContextClassLoader();
+        try {
+            
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+            addMetadataRecordImpl(new FileInputStream(input), name, 
input.length());
+            LOG.debug("Metadata record added. metadataName={} duration={}", 
name, watch.elapsed(TimeUnit.MILLISECONDS));
+        }
+        catch (FileNotFoundException e) {
+            throw new DataStoreException(e);
+        }
+        finally {
+            if (null != contextClassLoader) {
+                
Thread.currentThread().setContextClassLoader(contextClassLoader);
+            }
+        }
+    }
+
+    private void addMetadataRecordImpl(final InputStream input, String name, 
long recordLength) throws DataStoreException {
+        try {
+            CloudBlobDirectory metaDir = 
getAzureContainer().getDirectoryReference(AZURE_BlOB_META_DIR_NAME);
+            CloudBlockBlob blob = metaDir.getBlockBlobReference(name);
+            addLastModified(blob);
+            blob.upload(input, recordLength);
+        }
+        catch (StorageException e) {
+            LOG.info("Error adding metadata record. metadataName={} 
length={}", name, recordLength, e);
+            throw new DataStoreException(e);
+        }
+        catch (URISyntaxException |  IOException e) {
+            throw new DataStoreException(e);

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to