CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-azure--azure-core

Azure Core provides shared primitives, abstractions, and helpers for modern Java Azure SDK client libraries

Pending
Overview
Eval results
Files

http-policies.mddocs/

HTTP Pipeline Policies

Comprehensive HTTP pipeline policies providing cross-cutting concerns like authentication, retry, logging, and request modification. These policies enable modular request/response processing with configurable behavior.

Capabilities

Core Policy Interfaces

Base interfaces for creating custom HTTP pipeline policies.

/**
 * Interface for policies that can be added to the HttpPipeline.
 */
interface HttpPipelinePolicy {
    /**
     * Processes provided request context and invokes the next policy.
     * @param context The request context
     * @param next The next HTTP pipeline policy to process
     * @return A Mono that emits an HttpResponse
     */
    Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Interface for synchronous HTTP pipeline policies.
 */
interface HttpPipelineSyncPolicy extends HttpPipelinePolicy {
    /**
     * Processes provided request context and invokes the next policy synchronously.
     * @param context The request context
     * @param next The next HTTP pipeline policy to process
     * @return The HttpResponse
     */
    HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next);
}

Authentication Policies

Policies for various authentication mechanisms.

/**
 * Pipeline policy that applies a Bearer token credential to requests as an Authorization header.
 */
class BearerTokenAuthenticationPolicy implements HttpPipelinePolicy {
    /**
     * Creates BearerTokenAuthenticationPolicy.
     * @param credential The token credential to authenticate requests
     * @param scopes The scopes required for the token
     */
    public BearerTokenAuthenticationPolicy(TokenCredential credential, String... scopes);
    
    /**
     * Creates BearerTokenAuthenticationPolicy with custom options.
     * @param credential The token credential to authenticate requests
     * @param scopes The scopes required for the token
     * @param challengeHandler Custom challenge handler for handling authentication challenges
     */
    public BearerTokenAuthenticationPolicy(TokenCredential credential, String[] scopes, AuthenticationChallengeHandler challengeHandler);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that applies AzureKeyCredential to requests.
 */
class AzureKeyCredentialPolicy implements HttpPipelinePolicy {
    /**
     * Creates AzureKeyCredentialPolicy.
     * @param name The name of the key credential header or query parameter
     * @param credential The AzureKeyCredential used to authenticate requests
     * @param location Where to apply the key (HEADER or QUERY_PARAMETER)
     */
    public AzureKeyCredentialPolicy(String name, AzureKeyCredential credential, AzureKeyCredentialPolicy.KeyCredentialLocation location);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
    
    /**
     * Enum defining where the key credential should be applied.
     */
    enum KeyCredentialLocation {
        HEADER, QUERY_PARAMETER
    }
}

/**
 * Pipeline policy that applies AzureSasCredential to requests as a query parameter.
 */
class AzureSasCredentialPolicy implements HttpPipelinePolicy {
    /**
     * Creates AzureSasCredentialPolicy.
     * @param credential The AzureSasCredential used to authenticate requests
     */
    public AzureSasCredentialPolicy(AzureSasCredential credential);
    
    /**
     * Creates AzureSasCredentialPolicy with custom parameter name.
     * @param credential The AzureSasCredential used to authenticate requests
     * @param queryParameterName Custom query parameter name for the SAS token
     */
    public AzureSasCredentialPolicy(AzureSasCredential credential, String queryParameterName);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that applies KeyCredential to requests.
 */
class KeyCredentialPolicy implements HttpPipelinePolicy {
    /**
     * Creates KeyCredentialPolicy.
     * @param name The name of the key credential header
     * @param credential The KeyCredential used to authenticate requests
     */
    public KeyCredentialPolicy(String name, KeyCredential credential);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

Retry Policies

Policies for handling request retries with various strategies.

/**
 * Pipeline policy that retries requests when recoverable HTTP errors or exceptions occur.
 */
class RetryPolicy implements HttpPipelinePolicy {
    /**
     * Creates RetryPolicy with default retry options.
     */
    public RetryPolicy();
    
    /**
     * Creates RetryPolicy with custom retry options.
     * @param retryOptions The retry configuration options
     */
    public RetryPolicy(RetryOptions retryOptions);
    
    /**
     * Creates RetryPolicy with custom retry strategy.
     * @param retryStrategy Custom retry strategy implementation
     */
    public RetryPolicy(RetryStrategy retryStrategy);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Configuration options for retry behavior.
 */
class RetryOptions {
    /**
     * Creates RetryOptions with default settings.
     */
    public RetryOptions();
    
    /**
     * Gets the maximum number of retry attempts.
     * @return Maximum retry attempts
     */
    public int getMaxRetries();
    
    /**
     * Sets the maximum number of retry attempts.
     * @param maxRetries Maximum retry attempts (0-10)
     * @return Updated RetryOptions
     */
    public RetryOptions setMaxRetries(int maxRetries);
    
    /**
     * Gets the delay between retry attempts.
     * @return Delay duration
     */
    public Duration getDelay();
    
    /**
     * Sets the delay between retry attempts.
     * @param delay Delay duration
     * @return Updated RetryOptions
     */
    public RetryOptions setDelay(Duration delay);
    
    /**
     * Gets the maximum delay between retry attempts.
     * @return Maximum delay duration
     */
    public Duration getMaxDelay();
    
    /**
     * Sets the maximum delay between retry attempts.
     * @param maxDelay Maximum delay duration
     * @return Updated RetryOptions
     */
    public RetryOptions setMaxDelay(Duration maxDelay);
    
    /**
     * Gets the retry strategy.
     * @return Retry strategy
     */
    public RetryStrategy getRetryStrategy();
    
    /**
     * Sets the retry strategy.
     * @param retryStrategy Retry strategy implementation
     * @return Updated RetryOptions
     */
    public RetryOptions setRetryStrategy(RetryStrategy retryStrategy);
}

/**
 * Interface defining retry strategies.
 */
interface RetryStrategy {
    /**
     * Calculates the delay before the next retry attempt.
     * @param retryAttempt The current retry attempt number (1-based)
     * @param baseDelay The base delay duration
     * @param maxDelay The maximum allowed delay
     * @return The calculated delay duration
     */
    Duration calculateRetryDelay(int retryAttempt, Duration baseDelay, Duration maxDelay);
}

/**
 * Exponential backoff retry strategy.
 */
class ExponentialBackoff implements RetryStrategy {
    /**
     * Creates ExponentialBackoff with default options.
     */
    public ExponentialBackoff();
    
    /**
     * Creates ExponentialBackoff with custom options.
     * @param options Exponential backoff configuration
     */
    public ExponentialBackoff(ExponentialBackoffOptions options);
    
    @Override
    public Duration calculateRetryDelay(int retryAttempt, Duration baseDelay, Duration maxDelay);
}

/**
 * Fixed delay retry strategy.
 */
class FixedDelay implements RetryStrategy {
    /**
     * Creates FixedDelay with default options.
     */
    public FixedDelay();
    
    /**
     * Creates FixedDelay with custom options.
     * @param options Fixed delay configuration
     */
    public FixedDelay(FixedDelayOptions options);
    
    @Override
    public Duration calculateRetryDelay(int retryAttempt, Duration baseDelay, Duration maxDelay);
}

Logging Policies

Policies for HTTP request and response logging.

/**
 * Pipeline policy that handles logging of HTTP requests and responses.
 */
class HttpLoggingPolicy implements HttpPipelinePolicy {
    /**
     * Creates HttpLoggingPolicy with default options.
     */
    public HttpLoggingPolicy();
    
    /**
     * Creates HttpLoggingPolicy with custom options.
     * @param httpLogOptions HTTP logging configuration
     */
    public HttpLoggingPolicy(HttpLogOptions httpLogOptions);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Configuration for HTTP request and response logging.
 */
class HttpLogOptions {
    /**
     * Creates HttpLogOptions with default settings.
     */
    public HttpLogOptions();
    
    /**
     * Gets the logging detail level.
     * @return The logging detail level
     */
    public HttpLogDetailLevel getLogLevel();
    
    /**
     * Sets the logging detail level.
     * @param logLevel The logging detail level
     * @return Updated HttpLogOptions
     */
    public HttpLogOptions setLogLevel(HttpLogDetailLevel logLevel);
    
    /**
     * Gets the allowed header names for logging.
     * @return Set of allowed header names
     */
    public Set<String> getAllowedHeaderNames();
    
    /**
     * Sets the allowed header names for logging.
     * @param allowedHeaderNames Set of allowed header names
     * @return Updated HttpLogOptions
     */
    public HttpLogOptions setAllowedHeaderNames(Set<String> allowedHeaderNames);
    
    /**
     * Adds an allowed header name for logging.
     * @param allowedHeaderName Header name to allow
     * @return Updated HttpLogOptions
     */
    public HttpLogOptions addAllowedHeaderName(String allowedHeaderName);
    
    /**
     * Gets the allowed query parameter names for logging.
     * @return Set of allowed query parameter names
     */
    public Set<String> getAllowedQueryParamNames();
    
    /**
     * Sets the allowed query parameter names for logging.
     * @param allowedQueryParamNames Set of allowed query parameter names
     * @return Updated HttpLogOptions
     */
    public HttpLogOptions setAllowedQueryParamNames(Set<String> allowedQueryParamNames);
    
    /**
     * Adds an allowed query parameter name for logging.
     * @param allowedQueryParamName Query parameter name to allow
     * @return Updated HttpLogOptions
     */
    public HttpLogOptions addAllowedQueryParamName(String allowedQueryParamName);
    
    /**
     * Gets whether to pretty print JSON bodies.
     * @return Whether to pretty print JSON
     */
    public boolean isPrettyPrintBody();
    
    /**
     * Sets whether to pretty print JSON bodies.
     * @param prettyPrintBody Whether to pretty print JSON
     * @return Updated HttpLogOptions
     */
    public HttpLogOptions setPrettyPrintBody(boolean prettyPrintBody);
}

/**
 * Enumeration of HTTP logging detail levels.
 */
enum HttpLogDetailLevel {
    /**
     * No logging.
     */
    NONE,
    
    /**
     * Log only the request method and URL, and the response status code and execution time.
     */
    BASIC,
    
    /**
     * Log the basic information along with request and response headers.
     */
    HEADERS,
    
    /**
     * Log the headers information along with request and response body.
     */
    BODY,
    
    /**
     * Log everything including request and response bodies and headers.
     */
    BODY_AND_HEADERS
}

Request Modification Policies

Policies for modifying HTTP requests.

/**
 * Pipeline policy that adds headers to HTTP requests.
 */
class AddHeadersPolicy implements HttpPipelinePolicy {
    /**
     * Creates AddHeadersPolicy.
     * @param headers Headers to add to requests
     */
    public AddHeadersPolicy(HttpHeaders headers);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that adds headers from context to HTTP requests.
 */
class AddHeadersFromContextPolicy implements HttpPipelinePolicy {
    /**
     * Creates AddHeadersFromContextPolicy.
     */
    public AddHeadersFromContextPolicy();
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that adds the current date to HTTP requests.
 */
class AddDatePolicy implements HttpPipelinePolicy {
    /**
     * Creates AddDatePolicy.
     */
    public AddDatePolicy();
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that sets the User-Agent header.
 */
class UserAgentPolicy implements HttpPipelinePolicy {
    /**
     * Creates UserAgentPolicy with application ID.
     * @param applicationId The application identifier
     */
    public UserAgentPolicy(String applicationId);
    
    /**
     * Creates UserAgentPolicy with custom user agent string.
     * @param applicationId The application identifier
     * @param applicationVersion The application version
     * @param configuration Configuration for additional user agent information
     */
    public UserAgentPolicy(String applicationId, String applicationVersion, Configuration configuration);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that adds a request ID to HTTP requests.
 */
class RequestIdPolicy implements HttpPipelinePolicy {
    /**
     * Creates RequestIdPolicy with default request ID header.
     */
    public RequestIdPolicy();
    
    /**
     * Creates RequestIdPolicy with custom request ID header name.
     * @param requestIdHeaderName Custom header name for request ID
     */
    public RequestIdPolicy(String requestIdHeaderName);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that handles request timeouts.
 */
class TimeoutPolicy implements HttpPipelinePolicy {
    /**
     * Creates TimeoutPolicy.
     * @param timeout The timeout duration for requests
     */
    public TimeoutPolicy(Duration timeout);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

Redirect and Network Policies

Policies for handling redirects and network-level concerns.

/**
 * Pipeline policy that handles HTTP redirects.
 */
class RedirectPolicy implements HttpPipelinePolicy {
    /**
     * Creates RedirectPolicy with default redirect strategy.
     */
    public RedirectPolicy();
    
    /**
     * Creates RedirectPolicy with custom redirect strategy.
     * @param redirectStrategy Custom redirect handling strategy
     */
    public RedirectPolicy(RedirectStrategy redirectStrategy);
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Interface for redirect handling strategies.
 */
interface RedirectStrategy {
    /**
     * Determines if a request should be redirected based on the response.
     * @param httpRequest The original HTTP request
     * @param httpResponse The HTTP response indicating a redirect
     * @param redirectAttempt The number of redirect attempts so far
     * @param maxRedirects The maximum number of allowed redirects
     * @return true if the request should be redirected, false otherwise
     */
    boolean shouldRedirect(HttpRequest httpRequest, HttpResponse httpResponse, int redirectAttempt, int maxRedirects);
    
    /**
     * Creates a redirect request based on the original request and response.
     * @param httpRequest The original HTTP request
     * @param httpResponse The HTTP response indicating a redirect
     * @param redirectAttempt The number of redirect attempts so far
     * @return The redirect HTTP request, or null if redirect should not happen
     */
    HttpRequest createRedirectRequest(HttpRequest httpRequest, HttpResponse httpResponse, int redirectAttempt);
}

/**
 * Default implementation of redirect strategy.
 */
class DefaultRedirectStrategy implements RedirectStrategy {
    /**
     * Creates DefaultRedirectStrategy with default settings.
     */
    public DefaultRedirectStrategy();
    
    /**
     * Creates DefaultRedirectStrategy with custom maximum redirects.
     * @param maxRedirects Maximum number of redirects to follow
     */
    public DefaultRedirectStrategy(int maxRedirects);
    
    @Override
    public boolean shouldRedirect(HttpRequest httpRequest, HttpResponse httpResponse, int redirectAttempt, int maxRedirects);
    
    @Override
    public HttpRequest createRedirectRequest(HttpRequest httpRequest, HttpResponse httpResponse, int redirectAttempt);
}

/**
 * Pipeline policy that handles cookies.
 */
class CookiePolicy implements HttpPipelinePolicy {
    /**
     * Creates CookiePolicy.
     */
    public CookiePolicy();
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that ensures the correct host header.
 */
class HostPolicy implements HttpPipelinePolicy {
    /**
     * Creates HostPolicy.
     */
    public HostPolicy();
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that ensures the correct port in the URL.
 */
class PortPolicy implements HttpPipelinePolicy {
    /**
     * Creates PortPolicy.
     */
    public PortPolicy();
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

/**
 * Pipeline policy that ensures the correct protocol (HTTP/HTTPS).
 */
class ProtocolPolicy implements HttpPipelinePolicy {
    /**
     * Creates ProtocolPolicy.
     */
    public ProtocolPolicy();
    
    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next);
}

Policy Provider Interfaces

Interfaces for providing policies at different stages of the pipeline.

/**
 * Provider interface for policies that should be executed before retry policies.
 */
interface BeforeRetryPolicyProvider {
    /**
     * Gets the policies to execute before retry logic.
     * @return List of HttpPipelinePolicy instances
     */
    List<HttpPipelinePolicy> getPolicies();
}

/**
 * Provider interface for policies that should be executed after retry policies.
 */
interface AfterRetryPolicyProvider {
    /**
     * Gets the policies to execute after retry logic.
     * @return List of HttpPipelinePolicy instances
     */
    List<HttpPipelinePolicy> getPolicies();
}

/**
 * General provider interface for HTTP pipeline policies.
 */
interface HttpPolicyProvider {
    /**
     * Gets the HTTP pipeline policies provided by this provider.
     * @return List of HttpPipelinePolicy instances
     */
    List<HttpPipelinePolicy> getPolicies();
}

/**
 * Utility class for working with HTTP policy providers.
 */
class HttpPolicyProviders {
    /**
     * Adds a policy provider to be executed before retry policies.
     * @param provider The policy provider
     */
    public static void addBeforeRetryPolicyProvider(BeforeRetryPolicyProvider provider);
    
    /**
     * Adds a policy provider to be executed after retry policies.
     * @param provider The policy provider
     */
    public static void addAfterRetryPolicyProvider(AfterRetryPolicyProvider provider);
    
    /**
     * Gets all before retry policy providers.
     * @return List of BeforeRetryPolicyProvider instances
     */
    public static List<BeforeRetryPolicyProvider> getBeforeRetryPolicyProviders();
    
    /**
     * Gets all after retry policy providers.
     * @return List of AfterRetryPolicyProvider instances
     */
    public static List<AfterRetryPolicyProvider> getAfterRetryPolicyProviders();
}

Usage Examples

Basic Policy Pipeline Setup

import com.azure.core.http.*;
import com.azure.core.http.policy.*;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;

public class BasicPipelineSetup {
    
    public HttpPipeline createStandardPipeline(String endpoint) {
        TokenCredential credential = new DefaultAzureCredentialBuilder().build();
        
        return new HttpPipelineBuilder()
            .httpClient(HttpClient.createDefault())
            .policies(
                // Request modification policies
                new UserAgentPolicy("MyApp/1.0"),
                new RequestIdPolicy(),
                new AddDatePolicy(),
                
                // Authentication policy
                new BearerTokenAuthenticationPolicy(credential, "https://management.azure.com/.default"),
                
                // Retry policy
                new RetryPolicy(new RetryOptions()
                    .setMaxRetries(3)
                    .setDelay(Duration.ofSeconds(1))
                    .setMaxDelay(Duration.ofSeconds(10))),
                
                // Logging policy
                new HttpLoggingPolicy(new HttpLogOptions()
                    .setLogLevel(HttpLogDetailLevel.HEADERS)
                    .addAllowedHeaderName("x-ms-request-id")),
                
                // Redirect policy
                new RedirectPolicy()
            )
            .build();
    }
}

Custom Authentication Policy

import com.azure.core.http.policy.*;
import com.azure.core.credential.AzureKeyCredential;

public class CustomAuthenticationExample {
    
    public HttpPipeline createPipelineWithMultipleAuth(String apiKey, String sasToken) {
        return new HttpPipelineBuilder()
            .httpClient(HttpClient.createDefault())
            .policies(
                new UserAgentPolicy("MultiAuthApp/1.0"),
                
                // Multiple authentication policies
                new AzureKeyCredentialPolicy("x-api-key", 
                    new AzureKeyCredential(apiKey), 
                    AzureKeyCredentialPolicy.KeyCredentialLocation.HEADER),
                    
                new AzureSasCredentialPolicy(new AzureSasCredential(sasToken)),
                
                // Custom headers
                new AddHeadersPolicy(new HttpHeaders()
                    .put("x-custom-client", "MyApplication")
                    .put("Accept", "application/json")),
                
                new RetryPolicy(),
                new HttpLoggingPolicy()
            )
            .build();
    }
}

Advanced Retry Configuration

import com.azure.core.http.policy.*;
import java.time.Duration;

public class AdvancedRetryExample {
    
    public RetryPolicy createCustomRetryPolicy() {
        RetryOptions options = new RetryOptions()
            .setMaxRetries(5)
            .setDelay(Duration.ofMillis(500))
            .setMaxDelay(Duration.ofSeconds(30))
            .setRetryStrategy(new ExponentialBackoff(
                new ExponentialBackoffOptions()
                    .setBaseDelay(Duration.ofMillis(500))
                    .setMaxDelay(Duration.ofSeconds(30))));
        
        return new RetryPolicy(options);
    }
    
    // Custom retry strategy
    public class CustomRetryStrategy implements RetryStrategy {
        @Override
        public Duration calculateRetryDelay(int retryAttempt, Duration baseDelay, Duration maxDelay) {
            // Custom logic: fibonacci-like backoff
            long delayMs = Math.min(
                baseDelay.toMillis() * fibonacci(retryAttempt),
                maxDelay.toMillis()
            );
            return Duration.ofMillis(delayMs);
        }
        
        private long fibonacci(int n) {
            if (n <= 1) return n;
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
    }
}

Comprehensive Logging Setup

import com.azure.core.http.policy.*;
import java.util.Set;

public class ComprehensiveLoggingExample {
    
    public HttpLoggingPolicy createDetailedLoggingPolicy() {
        HttpLogOptions options = new HttpLogOptions()
            .setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
            .setPrettyPrintBody(true)
            
            // Allow specific headers to be logged
            .setAllowedHeaderNames(Set.of(
                "x-ms-request-id",
                "x-ms-correlation-request-id", 
                "x-ms-client-request-id",
                "Content-Type",
                "Accept"
            ))
            
            // Allow specific query parameters to be logged
            .setAllowedQueryParamNames(Set.of(
                "api-version",
                "timeout",
                "$filter",
                "$select"
            ));
        
        return new HttpLoggingPolicy(options);
    }
}

Custom Policy Implementation

import com.azure.core.http.policy.*;
import reactor.core.publisher.Mono;

public class CustomPolicyExample {
    
    // Rate limiting policy
    public static class RateLimitingPolicy implements HttpPipelinePolicy {
        private final Semaphore semaphore;
        
        public RateLimitingPolicy(int maxConcurrentRequests) {
            this.semaphore = new Semaphore(maxConcurrentRequests);
        }
        
        @Override
        public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
            return Mono.fromCallable(() -> {
                semaphore.acquire();
                return true;
            })
            .flatMap(ignored -> next.process())
            .doFinally(signal -> semaphore.release());
        }
    }
    
    // Request correlation policy
    public static class CorrelationIdPolicy implements HttpPipelinePolicy {
        private final String correlationIdHeader;
        
        public CorrelationIdPolicy() {
            this("x-correlation-id");
        }
        
        public CorrelationIdPolicy(String correlationIdHeader) {
            this.correlationIdHeader = correlationIdHeader;
        }
        
        @Override
        public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
            HttpRequest request = context.getHttpRequest();
            
            // Add correlation ID if not present
            if (request.getHeaders().getValue(correlationIdHeader) == null) {
                String correlationId = UUID.randomUUID().toString();
                request.setHeader(correlationIdHeader, correlationId);
                
                // Also add to context for logging
                context.setData("correlationId", correlationId);
            }
            
            return next.process();
        }
    }
    
    // Circuit breaker policy
    public static class CircuitBreakerPolicy implements HttpPipelinePolicy {
        private volatile CircuitState state = CircuitState.CLOSED;
        private final AtomicInteger failureCount = new AtomicInteger(0);
        private volatile Instant lastFailureTime = Instant.MIN;
        private final int failureThreshold;
        private final Duration timeoutDuration;
        
        public CircuitBreakerPolicy(int failureThreshold, Duration timeoutDuration) {
            this.failureThreshold = failureThreshold;
            this.timeoutDuration = timeoutDuration;
        }
        
        @Override
        public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
            if (state == CircuitState.OPEN) {
                if (Instant.now().isAfter(lastFailureTime.plus(timeoutDuration))) {
                    state = CircuitState.HALF_OPEN;
                } else {
                    return Mono.error(new RuntimeException("Circuit breaker is OPEN"));
                }
            }
            
            return next.process()
                .doOnSuccess(response -> {
                    if (response.getStatusCode() >= 500) {
                        recordFailure();
                    } else {
                        recordSuccess();
                    }
                })
                .doOnError(error -> recordFailure());
        }
        
        private void recordFailure() {
            failureCount.incrementAndGet();
            lastFailureTime = Instant.now();
            
            if (failureCount.get() >= failureThreshold) {
                state = CircuitState.OPEN;
            }
        }
        
        private void recordSuccess() {
            failureCount.set(0);
            state = CircuitState.CLOSED;
        }
        
        enum CircuitState {
            CLOSED, OPEN, HALF_OPEN
        }
    }
}

Policy Provider Implementation

import com.azure.core.http.policy.*;
import java.util.List;

public class CustomPolicyProviderExample {
    
    // Before retry policy provider
    public static class SecurityPolicyProvider implements BeforeRetryPolicyProvider {
        @Override
        public List<HttpPipelinePolicy> getPolicies() {
            return List.of(
                new CustomPolicyExample.CorrelationIdPolicy(),
                new RequestIdPolicy(),
                new AddHeadersPolicy(new HttpHeaders()
                    .put("X-Security-Token", "security-header-value")
                    .put("X-Client-Version", "1.0.0"))
            );
        }
    }
    
    // After retry policy provider  
    public static class InstrumentationPolicyProvider implements AfterRetryPolicyProvider {
        @Override
        public List<HttpPipelinePolicy> getPolicies() {
            return List.of(
                new HttpLoggingPolicy(new HttpLogOptions()
                    .setLogLevel(HttpLogDetailLevel.BASIC)),
                new CustomPolicyExample.RateLimitingPolicy(10),
                new TimeoutPolicy(Duration.ofSeconds(30))
            );
        }
    }
    
    // Usage with policy providers
    public void setupPipelineWithProviders() {
        // Register policy providers
        HttpPolicyProviders.addBeforeRetryPolicyProvider(new SecurityPolicyProvider());
        HttpPolicyProviders.addAfterRetryPolicyProvider(new InstrumentationPolicyProvider());
        
        // Create pipeline - providers will be automatically included
        HttpPipeline pipeline = new HttpPipelineBuilder()
            .httpClient(HttpClient.createDefault())
            .policies(
                new UserAgentPolicy("MyApp/1.0"),
                new BearerTokenAuthenticationPolicy(credential, scopes),
                new RetryPolicy()
            )
            .build();
    }
}

Policy Ordering and Coordination

import com.azure.core.http.policy.*;

public class PolicyOrderingExample {
    
    public HttpPipeline createWellOrderedPipeline() {
        return new HttpPipelineBuilder()
            .httpClient(HttpClient.createDefault())
            .policies(
                // 1. Request preparation policies (should be first)
                new UserAgentPolicy("MyApp/1.0"),
                new RequestIdPolicy(),
                new AddDatePolicy(),
                new ProtocolPolicy(),
                new HostPolicy(),
                new PortPolicy(),
                
                // 2. Request modification policies
                new AddHeadersPolicy(createCommonHeaders()),
                new AddHeadersFromContextPolicy(),
                
                // 3. Authentication policies (before retry so failed auth doesn't get retried unnecessarily)
                new BearerTokenAuthenticationPolicy(credential, scopes),
                
                // 4. Before retry policies (custom policies that should run before retry)
                new CustomPolicyExample.CorrelationIdPolicy(),
                new CustomPolicyExample.CircuitBreakerPolicy(5, Duration.ofMinutes(1)),
                
                // 5. Retry policy (central retry logic)
                new RetryPolicy(new RetryOptions()
                    .setMaxRetries(3)
                    .setDelay(Duration.ofSeconds(1))),
                
                // 6. After retry policies
                new CustomPolicyExample.RateLimitingPolicy(20),
                new TimeoutPolicy(Duration.ofSeconds(60)),
                
                // 7. Response handling policies
                new RedirectPolicy(new DefaultRedirectStrategy(5)),
                new CookiePolicy(),
                
                // 8. Logging policy (should be last to capture the final request/response)
                new HttpLoggingPolicy(new HttpLogOptions()
                    .setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
            )
            .build();
    }
    
    private HttpHeaders createCommonHeaders() {
        return new HttpHeaders()
            .put("Accept", "application/json")
            .put("Content-Type", "application/json")
            .put("X-Client-Name", "MyApplication");
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-com-azure--azure-core

docs

annotations.md

authentication.md

client-traits.md

cryptography.md

exceptions.md

http-client.md

http-policies.md

index.md

models.md

serialization.md

utilities.md

tile.json