or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations.mdauthentication.mdclient-traits.mdcryptography.mdexceptions.mdhttp-client.mdhttp-policies.mdindex.mdmodels.mdserialization.mdutilities.md

utilities.mddocs/

0

# Utility Classes

1

2

Essential utilities including configuration management, logging, metrics, tracing, polling operations, and helper functions for Azure SDK development.

3

4

## Capabilities

5

6

### Configuration Management

7

8

Centralized configuration system supporting environment variables, system properties, and programmatic configuration.

9

10

```java { .api }

11

/**

12

* Contains configuration information used to build client libraries.

13

*/

14

class Configuration {

15

/**

16

* Gets the global configuration instance.

17

* @return Global Configuration instance

18

*/

19

public static Configuration getGlobalConfiguration();

20

21

/**

22

* Creates a new Configuration instance.

23

*/

24

public Configuration();

25

26

/**

27

* Creates a Configuration instance with the provided configuration source.

28

* @param configurationSource Source of configuration values

29

*/

30

public Configuration(ConfigurationSource configurationSource);

31

32

/**

33

* Gets the value of the configuration.

34

* @param name Name of the configuration property

35

* @return Configuration value or null if not found

36

*/

37

public String get(String name);

38

39

/**

40

* Gets the value of the configuration.

41

* @param name Name of the configuration property

42

* @param defaultValue Default value if configuration is not found

43

* @return Configuration value or default value

44

*/

45

public String get(String name, String defaultValue);

46

47

/**

48

* Gets the value of the configuration and converts it to the specified type.

49

* @param <T> Type to convert to

50

* @param name Name of the configuration property

51

* @param converter Function to convert string to desired type

52

* @return Converted configuration value or null

53

*/

54

public <T> T get(String name, Function<String, T> converter);

55

56

/**

57

* Gets the value of the configuration and converts it to the specified type.

58

* @param <T> Type to convert to

59

* @param name Name of the configuration property

60

* @param converter Function to convert string to desired type

61

* @param defaultValue Default value if configuration is not found

62

* @return Converted configuration value or default value

63

*/

64

public <T> T get(String name, Function<String, T> converter, T defaultValue);

65

66

/**

67

* Gets the value of the configuration with generic default value.

68

* @param <T> Type of the configuration value

69

* @param name Name of the configuration property

70

* @param defaultValue Default value if configuration is not found

71

* @return Configuration value or default value

72

*/

73

public <T> T get(String name, T defaultValue);

74

75

/**

76

* Gets the value of the configuration property.

77

* @param <T> Type of the configuration property

78

* @param property The configuration property

79

* @return Configuration value or null if not found

80

*/

81

public <T> T get(ConfigurationProperty<T> property);

82

83

/**

84

* Determines if the configuration contains the specified property.

85

* @param property The configuration property to check

86

* @return true if the configuration contains the property

87

*/

88

public boolean contains(ConfigurationProperty<?> property);

89

90

/**

91

* Adds a configuration property.

92

* @param name Name of the configuration property

93

* @param value Value of the configuration property

94

* @return Updated Configuration instance

95

*/

96

public Configuration put(String name, String value);

97

98

/**

99

* Removes a configuration property.

100

* @param name Name of the configuration property to remove

101

* @return Updated Configuration instance

102

*/

103

public Configuration remove(String name);

104

105

/**

106

* Determines if the configuration contains the specified property.

107

* @param name Name of the configuration property

108

* @return true if the configuration contains the property

109

*/

110

public boolean contains(String name);

111

112

/**

113

* Creates a clone of the Configuration object.

114

* @return Cloned Configuration instance

115

*/

116

public Configuration clone();

117

}

118

119

/**

120

* Represents configuration property with type safety and validation.

121

*/

122

class ConfigurationProperty<T> {

123

/**

124

* Gets the property name.

125

* @return Property name

126

*/

127

public String getName();

128

129

/**

130

* Gets the default value for the property.

131

* @return Default value

132

*/

133

public T getDefaultValue();

134

135

/**

136

* Converts string value to property type.

137

* @param value String value to convert

138

* @return Converted value

139

*/

140

public T convert(String value);

141

}

142

143

/**

144

* Builder for Configuration instances.

145

*/

146

class ConfigurationBuilder {

147

/**

148

* Creates a ConfigurationBuilder.

149

*/

150

public ConfigurationBuilder();

151

152

/**

153

* Adds a configuration source.

154

* @param configurationSource Source to add

155

* @return Updated ConfigurationBuilder

156

*/

157

public ConfigurationBuilder putConfigurationSource(ConfigurationSource configurationSource);

158

159

/**

160

* Builds the Configuration instance.

161

* @return Configuration instance

162

*/

163

public Configuration build();

164

}

165

166

/**

167

* Interface for configuration sources.

168

*/

169

interface ConfigurationSource {

170

/**

171

* Gets properties from the configuration source.

172

* @param name Property name

173

* @return Property value or null if not found

174

*/

175

String getPropertyValue(String name);

176

}

177

```

178

179

### Context Management

180

181

Thread-safe context system for passing metadata through call chains.

182

183

```java { .api }

184

/**

185

* Context offers a means of passing arbitrary data (key-value pairs) to pipeline policies.

186

*/

187

class Context {

188

/**

189

* Signifies that no data needs to be passed to the pipeline.

190

*/

191

public static final Context NONE;

192

193

/**

194

* Constructs a new Context object with the specified key-value pair.

195

* @param key The key with which the specified value should be associated

196

* @param value The value to be associated with the specified key

197

* @throws IllegalArgumentException If key is null

198

*/

199

public Context(Object key, Object value);

200

201

/**

202

* Adds a new immutable Context object with the specified key-value pair to the existing Context chain.

203

* @param key The key with which the specified value is to be associated

204

* @param value The value to be associated with the specified key

205

* @return Context object containing the specified pair added to the set of pairs

206

* @throws IllegalArgumentException If key is null

207

*/

208

public Context addData(Object key, Object value);

209

210

/**

211

* Gets the value associated with the specified key.

212

* @param key The key whose associated value is to be returned

213

* @return Optional containing the value associated with the key, empty Optional otherwise

214

* @throws IllegalArgumentException If key is null

215

*/

216

public Optional<Object> getData(Object key);

217

218

/**

219

* Gets all values as a Map.

220

* @return Map containing all key-value pairs in the context

221

*/

222

public Map<Object, Object> getValues();

223

}

224

```

225

226

### Logging System

227

228

Structured logging system optimized for Azure SDK usage patterns.

229

230

```java { .api }

231

/**

232

* This class is a logging abstraction layer over SLF4J.

233

*/

234

class ClientLogger {

235

/**

236

* Creates a ClientLogger for the specified class.

237

* @param clazz Class to create logger for

238

*/

239

public ClientLogger(Class<?> clazz);

240

241

/**

242

* Creates a ClientLogger with the specified name.

243

* @param className Name for the logger

244

*/

245

public ClientLogger(String className);

246

247

/**

248

* Logs a message at verbose level.

249

* @param message Message to log

250

*/

251

public void verbose(String message);

252

253

/**

254

* Logs a message with arguments at verbose level.

255

* @param format Message format string

256

* @param args Arguments for the format string

257

*/

258

public void verbose(String format, Object... args);

259

260

/**

261

* Logs an informational message.

262

* @param message Message to log

263

*/

264

public void info(String message);

265

266

/**

267

* Logs an informational message with arguments.

268

* @param format Message format string

269

* @param args Arguments for the format string

270

*/

271

public void info(String format, Object... args);

272

273

/**

274

* Logs a warning message.

275

* @param message Message to log

276

*/

277

public void warning(String message);

278

279

/**

280

* Logs a warning message with arguments.

281

* @param format Message format string

282

* @param args Arguments for the format string

283

*/

284

public void warning(String format, Object... args);

285

286

/**

287

* Logs an error message.

288

* @param message Message to log

289

*/

290

public void error(String message);

291

292

/**

293

* Logs an error message with throwable.

294

* @param message Message to log

295

* @param throwable Exception to log

296

*/

297

public void error(String message, Throwable throwable);

298

299

/**

300

* Logs an error message with arguments.

301

* @param format Message format string

302

* @param args Arguments for the format string

303

*/

304

public void error(String format, Object... args);

305

306

/**

307

* Determines if logging is enabled for the specified log level.

308

* @param logLevel Log level to check

309

* @return true if logging is enabled for the level

310

*/

311

public boolean canLogAtLevel(LogLevel logLevel);

312

313

/**

314

* Logs a message at the specified level.

315

* @param logLevel Level to log at

316

* @param message Message to log

317

*/

318

public void log(LogLevel logLevel, String message);

319

320

/**

321

* Logs a message with arguments at the specified level.

322

* @param logLevel Level to log at

323

* @param format Message format string

324

* @param args Arguments for the format string

325

*/

326

public void log(LogLevel logLevel, String format, Object... args);

327

328

/**

329

* Logs a message with throwable at the specified level.

330

* @param logLevel Level to log at

331

* @param message Message to log

332

* @param throwable Exception to log

333

*/

334

public void log(LogLevel logLevel, String message, Throwable throwable);

335

}

336

337

/**

338

* Enumeration of log levels.

339

*/

340

enum LogLevel {

341

/**

342

* Indicates that log level is not set.

343

*/

344

NOT_SET(0),

345

346

/**

347

* Verbose logging level.

348

*/

349

VERBOSE(1),

350

351

/**

352

* Informational logging level.

353

*/

354

INFORMATIONAL(2),

355

356

/**

357

* Warning logging level.

358

*/

359

WARNING(3),

360

361

/**

362

* Error logging level.

363

*/

364

ERROR(4);

365

366

private final int value;

367

368

LogLevel(int value) {

369

this.value = value;

370

}

371

372

/**

373

* Gets the numeric value of the log level.

374

* @return Numeric value

375

*/

376

public int getValue() {

377

return value;

378

}

379

380

/**

381

* Creates LogLevel from numeric value.

382

* @param value Numeric value

383

* @return Corresponding LogLevel

384

*/

385

public static LogLevel fromValue(int value);

386

}

387

```

388

389

### Polling Operations

390

391

Support for long-running operations with automatic polling and completion detection.

392

393

```java { .api }

394

/**

395

* Synchronous poller for long-running operations.

396

*/

397

class SyncPoller<T, U> {

398

/**

399

* Polls and returns the current status of the long-running operation.

400

* @return PollResponse representing the current status

401

*/

402

public PollResponse<T> poll();

403

404

/**

405

* Waits for polling to complete.

406

* @return Final PollResponse when operation completes

407

*/

408

public PollResponse<T> waitForCompletion();

409

410

/**

411

* Waits for polling to complete within the specified timeout.

412

* @param timeout Maximum time to wait

413

* @return Final PollResponse when operation completes

414

*/

415

public PollResponse<T> waitForCompletion(Duration timeout);

416

417

/**

418

* Waits until the long-running operation reaches a specified status.

419

* @param statusToWaitFor Status to wait for

420

* @return PollResponse when the specified status is reached

421

*/

422

public PollResponse<T> waitUntil(LongRunningOperationStatus statusToWaitFor);

423

424

/**

425

* Waits until the long-running operation reaches a specified status within timeout.

426

* @param statusToWaitFor Status to wait for

427

* @param timeout Maximum time to wait

428

* @return PollResponse when the specified status is reached

429

*/

430

public PollResponse<T> waitUntil(LongRunningOperationStatus statusToWaitFor, Duration timeout);

431

432

/**

433

* Gets the final result of the long-running operation.

434

* @return Final result when operation completes

435

*/

436

public U getFinalResult();

437

438

/**

439

* Cancels the long-running operation.

440

*/

441

public void cancelOperation();

442

443

/**

444

* Gets the polling interval.

445

* @return Duration between polls

446

*/

447

public Duration getPollInterval();

448

}

449

450

/**

451

* Asynchronous poller for long-running operations.

452

*/

453

class PollerFlux<T, U> {

454

/**

455

* Creates a PollerFlux instance.

456

* @param pollInterval Duration between polling attempts

457

* @param pollOperation Function that performs polling

458

* @param cancelOperation Function that cancels the operation

459

* @param fetchResultOperation Function that fetches the final result

460

* @return PollerFlux instance

461

*/

462

public static <T, U> PollerFlux<T, U> create(

463

Duration pollInterval,

464

Function<PollingContext<T>, Mono<PollResponse<T>>> pollOperation,

465

Function<PollingContext<T>, Mono<T>> cancelOperation,

466

Function<PollingContext<T>, Mono<U>> fetchResultOperation);

467

468

/**

469

* Subscribes to the polling flux.

470

* @return Flux of PollResponse objects

471

*/

472

public Flux<PollResponse<T>> flux();

473

474

/**

475

* Gets the final result when polling completes.

476

* @return Mono containing the final result

477

*/

478

public Mono<U> getFinalResult();

479

480

/**

481

* Cancels the long-running operation.

482

* @return Mono representing the cancellation operation

483

*/

484

public Mono<T> cancelOperation();

485

486

/**

487

* Gets the last polling response.

488

* @return Mono containing the last poll response

489

*/

490

public Mono<PollResponse<T>> getLastPollResponse();

491

492

/**

493

* Creates a SyncPoller from this PollerFlux.

494

* @return SyncPoller instance

495

*/

496

public SyncPoller<T, U> getSyncPoller();

497

}

498

499

/**

500

* Response from a polling operation.

501

*/

502

class PollResponse<T> {

503

/**

504

* Creates a PollResponse.

505

* @param status Status of the long-running operation

506

* @param value Current value from the service

507

*/

508

public PollResponse(LongRunningOperationStatus status, T value);

509

510

/**

511

* Creates a PollResponse.

512

* @param status Status of the long-running operation

513

* @param value Current value from the service

514

* @param retryAfter Suggested retry interval

515

*/

516

public PollResponse(LongRunningOperationStatus status, T value, Duration retryAfter);

517

518

/**

519

* Gets the status of the long-running operation.

520

* @return Operation status

521

*/

522

public LongRunningOperationStatus getStatus();

523

524

/**

525

* Gets the current value from the service.

526

* @return Current poll value

527

*/

528

public T getValue();

529

530

/**

531

* Gets the suggested retry interval.

532

* @return Retry interval or null if not specified

533

*/

534

public Duration getRetryAfter();

535

}

536

537

/**

538

* Represents the status of a long-running operation.

539

*/

540

enum LongRunningOperationStatus {

541

/**

542

* The operation is not started.

543

*/

544

NOT_STARTED,

545

546

/**

547

* The operation is in progress.

548

*/

549

IN_PROGRESS,

550

551

/**

552

* The operation completed successfully.

553

*/

554

SUCCESSFULLY_COMPLETED,

555

556

/**

557

* The operation failed.

558

*/

559

FAILED,

560

561

/**

562

* The operation was cancelled.

563

*/

564

USER_CANCELLED;

565

566

/**

567

* Checks if the status represents a completed operation.

568

* @return true if operation is complete

569

*/

570

public boolean isComplete() {

571

return this == SUCCESSFULLY_COMPLETED || this == FAILED || this == USER_CANCELLED;

572

}

573

}

574

575

/**

576

* Context passed to polling operations.

577

*/

578

class PollingContext<T> {

579

/**

580

* Gets the latest poll response.

581

* @return Latest PollResponse

582

*/

583

public PollResponse<T> getLatestResponse();

584

585

/**

586

* Sets data in the polling context.

587

* @param key Data key

588

* @param value Data value

589

*/

590

public void setData(String key, Object value);

591

592

/**

593

* Gets data from the polling context.

594

* @param key Data key

595

* @return Data value or null if not found

596

*/

597

public Object getData(String key);

598

599

/**

600

* Gets the HTTP pipeline for making requests.

601

* @return HttpPipeline instance

602

*/

603

public HttpPipeline getHttpPipeline();

604

605

/**

606

* Gets the serializer adapter.

607

* @return SerializerAdapter instance

608

*/

609

public SerializerAdapter getSerializerAdapter();

610

}

611

```

612

613

### Utility Classes

614

615

```java { .api }

616

/**

617

* Utility methods for Azure Core functionality.

618

*/

619

class CoreUtils {

620

/**

621

* Checks if a string is null or empty.

622

* @param string String to check

623

* @return true if string is null or empty

624

*/

625

public static boolean isNullOrEmpty(String string);

626

627

/**

628

* Gets the first non-null value from the provided options.

629

* @param <T> Type of the values

630

* @param values Values to check

631

* @return First non-null value or null if all are null

632

*/

633

@SafeVarargs

634

public static <T> T firstNonNull(T... values);

635

636

/**

637

* Creates a deep copy of the provided object using serialization.

638

* @param <T> Type of the object

639

* @param object Object to clone

640

* @param clazz Class of the object

641

* @return Deep copy of the object

642

*/

643

public static <T> T clone(T object, Class<T> clazz);

644

645

/**

646

* Gets the application ID from the configuration.

647

* @param configuration Configuration instance

648

* @return Application ID or null if not configured

649

*/

650

public static String getApplicationId(Configuration configuration);

651

652

/**

653

* Extracts the error from a Mono or Flux.

654

* @param throwable Throwable from reactive stream

655

* @return Extracted Throwable

656

*/

657

public static Throwable extractAndWrapException(Throwable throwable);

658

659

/**

660

* Finds the first throwable in the causal chain that is an instance of the provided class.

661

* @param <T> Type of throwable to find

662

* @param throwable Root throwable

663

* @param clazz Class to search for

664

* @return First matching throwable or null

665

*/

666

public static <T extends Throwable> T findFirstOfType(Throwable throwable, Class<T> clazz);

667

}

668

669

/**

670

* Utility methods for working with Reactor Flux.

671

*/

672

class FluxUtil {

673

/**

674

* Collects ByteBuffer Flux into a single byte array.

675

* @param stream Flux of ByteBuffer

676

* @return Mono containing collected byte array

677

*/

678

public static Mono<byte[]> collectBytesInByteBufferStream(Flux<ByteBuffer> stream);

679

680

/**

681

* Converts a ByteBuffer Flux to a BinaryData.

682

* @param stream Flux of ByteBuffer

683

* @return Mono containing BinaryData

684

*/

685

public static Mono<BinaryData> toBinaryData(Flux<ByteBuffer> stream);

686

687

/**

688

* Writes a ByteBuffer Flux to an OutputStream.

689

* @param stream Flux of ByteBuffer

690

* @param outputStream Target OutputStream

691

* @return Mono representing the write operation

692

*/

693

public static Mono<Void> writeToOutputStream(Flux<ByteBuffer> stream, OutputStream outputStream);

694

695

/**

696

* Creates a Flux that emits after a delay with exponential backoff.

697

* @param delay Initial delay

698

* @param maxRetries Maximum number of retries

699

* @return Flux with exponential backoff

700

*/

701

public static Flux<Long> createExponentialBackoffFlux(Duration delay, int maxRetries);

702

}

703

704

/**

705

* Entity tag utility for HTTP caching.

706

*/

707

class ETag {

708

/**

709

* The wildcard ETag.

710

*/

711

public static final ETag ALL = new ETag("*");

712

713

/**

714

* Creates an ETag.

715

* @param eTag ETag string value

716

*/

717

public ETag(String eTag);

718

719

/**

720

* Gets the ETag value.

721

* @return ETag string

722

*/

723

public String toString();

724

725

/**

726

* Checks if this ETag equals another.

727

* @param other Other ETag to compare

728

* @return true if equal

729

*/

730

@Override

731

public boolean equals(Object other);

732

733

/**

734

* Gets the hash code.

735

* @return Hash code

736

*/

737

@Override

738

public int hashCode();

739

}

740

741

/**

742

* Builder for constructing URLs.

743

*/

744

class UrlBuilder {

745

/**

746

* Creates a UrlBuilder.

747

*/

748

public UrlBuilder();

749

750

/**

751

* Sets the scheme (protocol).

752

* @param scheme URL scheme

753

* @return Updated UrlBuilder

754

*/

755

public UrlBuilder setScheme(String scheme);

756

757

/**

758

* Sets the host.

759

* @param host URL host

760

* @return Updated UrlBuilder

761

*/

762

public UrlBuilder setHost(String host);

763

764

/**

765

* Sets the port.

766

* @param port URL port

767

* @return Updated UrlBuilder

768

*/

769

public UrlBuilder setPort(int port);

770

771

/**

772

* Sets the path.

773

* @param path URL path

774

* @return Updated UrlBuilder

775

*/

776

public UrlBuilder setPath(String path);

777

778

/**

779

* Adds a query parameter.

780

* @param name Parameter name

781

* @param value Parameter value

782

* @return Updated UrlBuilder

783

*/

784

public UrlBuilder setQueryParameter(String name, String value);

785

786

/**

787

* Removes a query parameter.

788

* @param name Parameter name to remove

789

* @return Updated UrlBuilder

790

*/

791

public UrlBuilder removeQueryParameter(String name);

792

793

/**

794

* Builds the URL.

795

* @return Constructed URL

796

*/

797

public URL toURL();

798

799

/**

800

* Builds the URL string.

801

* @return URL as string

802

*/

803

public String toString();

804

}

805

```

806

807

### Paging Support

808

809

```java { .api }

810

/**

811

* Iterable stream that can be iterated multiple times.

812

*/

813

class IterableStream<T> implements Iterable<T> {

814

/**

815

* Creates an IterableStream from an Iterable.

816

* @param <T> Element type

817

* @param iterable Source iterable

818

* @return IterableStream instance

819

*/

820

public static <T> IterableStream<T> of(Iterable<T> iterable);

821

822

/**

823

* Gets an iterator over elements.

824

* @return Iterator over elements

825

*/

826

@Override

827

public Iterator<T> iterator();

828

829

/**

830

* Gets a stream of elements.

831

* @return Stream of elements

832

*/

833

public Stream<T> stream();

834

835

/**

836

* Applies a function to each element and returns a new IterableStream.

837

* @param <U> Result element type

838

* @param mapper Function to apply

839

* @return Mapped IterableStream

840

*/

841

public <U> IterableStream<U> map(Function<T, U> mapper);

842

843

/**

844

* Filters elements based on a predicate.

845

* @param predicate Filter predicate

846

* @return Filtered IterableStream

847

*/

848

public IterableStream<T> filter(Predicate<T> predicate);

849

}

850

851

/**

852

* Continuable page interface for paging operations.

853

*/

854

interface ContinuablePage<C, T> {

855

/**

856

* Gets the continuation token.

857

* @return Continuation token or null if no more pages

858

*/

859

C getContinuationToken();

860

861

/**

862

* Gets the elements on this page.

863

* @return Iterable of page elements

864

*/

865

IterableStream<T> getElements();

866

}

867

868

/**

869

* Synchronous paged iterable with continuation support.

870

*/

871

class ContinuablePagedIterable<C, T> extends PagedIterable<T> {

872

/**

873

* Gets pages as an iterable with continuation tokens.

874

* @return Iterable of pages

875

*/

876

public Iterable<ContinuablePage<C, T>> iterableByPage();

877

878

/**

879

* Gets pages starting from a continuation token.

880

* @param continuationToken Token to start from

881

* @return Iterable of pages

882

*/

883

public Iterable<ContinuablePage<C, T>> iterableByPage(C continuationToken);

884

885

/**

886

* Gets pages with a preferred page size.

887

* @param preferredPageSize Preferred number of elements per page

888

* @return Iterable of pages

889

*/

890

public Iterable<ContinuablePage<C, T>> iterableByPage(int preferredPageSize);

891

892

/**

893

* Gets pages starting from a continuation token with preferred page size.

894

* @param continuationToken Token to start from

895

* @param preferredPageSize Preferred number of elements per page

896

* @return Iterable of pages

897

*/

898

public Iterable<ContinuablePage<C, T>> iterableByPage(C continuationToken, int preferredPageSize);

899

}

900

901

/**

902

* Asynchronous paged flux with continuation support.

903

*/

904

class ContinuablePagedFlux<C, T> extends PagedFlux<T> {

905

/**

906

* Gets pages as a flux with continuation tokens.

907

* @return Flux of pages

908

*/

909

public Flux<ContinuablePage<C, T>> byPage();

910

911

/**

912

* Gets pages starting from a continuation token.

913

* @param continuationToken Token to start from

914

* @return Flux of pages

915

*/

916

public Flux<ContinuablePage<C, T>> byPage(C continuationToken);

917

918

/**

919

* Gets pages with a preferred page size.

920

* @param preferredPageSize Preferred number of elements per page

921

* @return Flux of pages

922

*/

923

public Flux<ContinuablePage<C, T>> byPage(int preferredPageSize);

924

925

/**

926

* Gets pages starting from a continuation token with preferred page size.

927

* @param continuationToken Token to start from

928

* @param preferredPageSize Preferred number of elements per page

929

* @return Flux of pages

930

*/

931

public Flux<ContinuablePage<C, T>> byPage(C continuationToken, int preferredPageSize);

932

}

933

```

934

935

## Usage Examples

936

937

### Configuration Management

938

939

```java

940

import com.azure.core.util.Configuration;

941

import com.azure.core.util.ConfigurationBuilder;

942

943

// Using global configuration

944

Configuration config = Configuration.getGlobalConfiguration();

945

946

// Get configuration values with defaults

947

String endpoint = config.get("AZURE_ENDPOINT", "https://default.azure.com");

948

int timeout = config.get("TIMEOUT", Integer::parseInt, 30);

949

boolean enableLogging = config.get("ENABLE_LOGGING", Boolean::parseBoolean, false);

950

951

// Programmatically set configuration

952

config.put("API_VERSION", "2023-01-01")

953

.put("MAX_RETRIES", "3");

954

955

// Create custom configuration

956

Configuration customConfig = new ConfigurationBuilder()

957

.putConfigurationSource(new MyCustomConfigSource())

958

.build();

959

960

// Check if configuration exists

961

if (config.contains("SECRET_KEY")) {

962

String secret = config.get("SECRET_KEY");

963

// Use secret

964

}

965

```

966

967

### Context Usage

968

969

```java

970

import com.azure.core.util.Context;

971

972

// Create context with metadata

973

Context context = Context.NONE

974

.addData("user-id", "user123")

975

.addData("correlation-id", UUID.randomUUID().toString())

976

.addData("operation", "create-user");

977

978

// Extract data from context

979

Optional<Object> userId = context.getData("user-id");

980

String correlationId = (String) context.getData("correlation-id").orElse(null);

981

982

// Pass context through operations

983

httpClient.send(request, context);

984

985

// Add HTTP request ID tracking

986

Context trackedContext = context.setHttpRequestId("req-456");

987

String requestId = trackedContext.getHttpRequestId();

988

```

989

990

### Logging Examples

991

992

```java

993

import com.azure.core.util.logging.ClientLogger;

994

import com.azure.core.util.logging.LogLevel;

995

996

class MyService {

997

private static final ClientLogger LOGGER = new ClientLogger(MyService.class);

998

999

public void processData(String data) {

1000

LOGGER.info("Processing data for request: {}", data);

1001

1002

try {

1003

// Process data

1004

LOGGER.verbose("Data processing steps completed successfully");

1005

} catch (Exception e) {

1006

LOGGER.error("Failed to process data", e);

1007

throw e;

1008

}

1009

}

1010

1011

public void conditionalLogging() {

1012

if (LOGGER.canLogAtLevel(LogLevel.VERBOSE)) {

1013

// Expensive operation only if verbose logging is enabled

1014

String expensiveDebugInfo = computeExpensiveDebugInfo();

1015

LOGGER.verbose("Debug info: {}", expensiveDebugInfo);

1016

}

1017

}

1018

}

1019

```

1020

1021

### Polling Operations

1022

1023

```java

1024

import com.azure.core.util.polling.*;

1025

import java.time.Duration;

1026

1027

// Synchronous polling

1028

SyncPoller<OperationStatus, String> poller = // ... create poller

1029

1030

// Poll until completion

1031

PollResponse<OperationStatus> finalResponse = poller.waitForCompletion();

1032

1033

// Poll with timeout

1034

PollResponse<OperationStatus> response = poller.waitForCompletion(Duration.ofMinutes(5));

1035

1036

// Wait for specific status

1037

poller.waitUntil(LongRunningOperationStatus.IN_PROGRESS);

1038

1039

// Get final result

1040

if (finalResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {

1041

String result = poller.getFinalResult();

1042

System.out.println("Operation completed: " + result);

1043

}

1044

1045

// Asynchronous polling

1046

PollerFlux<OperationStatus, String> asyncPoller = // ... create async poller

1047

1048

asyncPoller.flux()

1049

.doOnNext(pollResponse -> {

1050

System.out.println("Current status: " + pollResponse.getStatus());

1051

})

1052

.then(asyncPoller.getFinalResult())

1053

.subscribe(result -> {

1054

System.out.println("Final result: " + result);

1055

});

1056

```

1057

1058

### URL Building

1059

1060

```java

1061

import com.azure.core.util.UrlBuilder;

1062

1063

// Build complex URLs

1064

UrlBuilder builder = new UrlBuilder()

1065

.setScheme("https")

1066

.setHost("api.example.com")

1067

.setPort(443)

1068

.setPath("/v1/users")

1069

.setQueryParameter("limit", "50")

1070

.setQueryParameter("offset", "100")

1071

.setQueryParameter("filter", "active=true");

1072

1073

URL url = builder.toURL();

1074

String urlString = builder.toString();

1075

1076

// Modify existing URLs

1077

builder.removeQueryParameter("offset")

1078

.setQueryParameter("sort", "created_date");

1079

```

1080

1081

### Working with ETags

1082

1083

```java

1084

import com.azure.core.util.ETag;

1085

1086

// Create ETags

1087

ETag strongETag = new ETag("\"686897696a7c876b7e\"");

1088

ETag weakETag = new ETag("W/\"686897696a7c876b7e\"");

1089

ETag wildcardETag = ETag.ALL;

1090

1091

// Use in conditional requests

1092

HttpRequest request = new HttpRequest(HttpMethod.GET, url);

1093

request.setHeader("If-None-Match", strongETag.toString());

1094

1095

// Compare ETags

1096

if (eTag1.equals(eTag2)) {

1097

System.out.println("Resources are the same");

1098

}

1099

```

1100

1101

### Utility Operations

1102

1103

```java

1104

import com.azure.core.util.CoreUtils;

1105

import com.azure.core.util.FluxUtil;

1106

1107

// String utilities

1108

String value = CoreUtils.firstNonNull(null, "", "default");

1109

boolean isEmpty = CoreUtils.isNullOrEmpty(someString);

1110

1111

// Exception handling

1112

try {

1113

// Some operation

1114

} catch (Exception e) {

1115

Throwable rootCause = CoreUtils.findFirstOfType(e, IllegalArgumentException.class);

1116

if (rootCause != null) {

1117

// Handle specific exception type

1118

}

1119

}

1120

1121

// Flux utilities

1122

Flux<ByteBuffer> dataFlux = // ... get data flux

1123

Mono<byte[]> bytes = FluxUtil.collectBytesInByteBufferStream(dataFlux);

1124

Mono<BinaryData> binaryData = FluxUtil.toBinaryData(dataFlux);

1125

1126

// Write to output stream

1127

OutputStream outputStream = // ... get output stream

1128

FluxUtil.writeToOutputStream(dataFlux, outputStream).block();

1129

```

1130

1131

### HttpClientOptions

1132

1133

Configuration options for HTTP clients with timeout, proxy, and connection pool settings.

1134

1135

```java { .api }

1136

/**

1137

* General configuration options for HttpClients.

1138

*/

1139

class HttpClientOptions extends ClientOptions {

1140

/**

1141

* Creates a new instance of HttpClientOptions.

1142

*/

1143

public HttpClientOptions();

1144

1145

/**

1146

* Sets the proxy options that the HttpClient will use.

1147

* @param proxyOptions The proxy options to use

1148

* @return The updated HttpClientOptions object

1149

*/

1150

public HttpClientOptions setProxyOptions(ProxyOptions proxyOptions);

1151

1152

/**

1153

* Gets the proxy options that the HttpClient will use.

1154

* @return The proxy options to use

1155

*/

1156

public ProxyOptions getProxyOptions();

1157

1158

/**

1159

* Sets the configuration store that the HttpClient will use.

1160

* @param configuration The configuration store to use

1161

* @return The updated HttpClientOptions object

1162

*/

1163

public HttpClientOptions setConfiguration(Configuration configuration);

1164

1165

/**

1166

* Gets the configuration store that the HttpClient will use.

1167

* @return The configuration store to use

1168

*/

1169

public Configuration getConfiguration();

1170

1171

/**

1172

* Sets the connection timeout for a request to be sent.

1173

* @param connectTimeout Connect timeout duration

1174

* @return The updated HttpClientOptions object

1175

*/

1176

public HttpClientOptions setConnectTimeout(Duration connectTimeout);

1177

1178

/**

1179

* Gets the connection timeout for a request to be sent.

1180

* @return The connection timeout of a request to be sent

1181

*/

1182

public Duration getConnectTimeout();

1183

1184

/**

1185

* Sets the writing timeout for a request to be sent.

1186

* @param writeTimeout Write operation timeout duration

1187

* @return The updated HttpClientOptions object

1188

*/

1189

public HttpClientOptions setWriteTimeout(Duration writeTimeout);

1190

1191

/**

1192

* Gets the writing timeout for a request to be sent.

1193

* @return The writing timeout of a request to be sent

1194

*/

1195

public Duration getWriteTimeout();

1196

1197

/**

1198

* Sets the response timeout duration used when waiting for a server to reply.

1199

* @param responseTimeout Response timeout duration

1200

* @return The updated HttpClientOptions object

1201

*/

1202

public HttpClientOptions setResponseTimeout(Duration responseTimeout);

1203

1204

/**

1205

* Gets the response timeout duration used when waiting for a server to reply.

1206

* @return The response timeout duration

1207

*/

1208

public Duration getResponseTimeout();

1209

1210

/**

1211

* Sets the read timeout duration used when reading the server response.

1212

* @param readTimeout Read timeout duration

1213

* @return The updated HttpClientOptions object

1214

*/

1215

public HttpClientOptions setReadTimeout(Duration readTimeout);

1216

1217

/**

1218

* Gets the read timeout duration used when reading the server response.

1219

* @return The read timeout duration

1220

*/

1221

public Duration getReadTimeout();

1222

1223

/**

1224

* Sets the maximum connection pool size used by the underlying HTTP client.

1225

* @param maximumConnectionPoolSize The maximum connection pool size

1226

* @return The updated HttpClientOptions object

1227

*/

1228

public HttpClientOptions setMaximumConnectionPoolSize(Integer maximumConnectionPoolSize);

1229

1230

/**

1231

* Gets the maximum connection pool size used by the underlying HTTP client.

1232

* @return The maximum connection pool size

1233

*/

1234

public Integer getMaximumConnectionPoolSize();

1235

1236

/**

1237

* Sets the duration of time before an idle connection.

1238

* @param connectionIdleTimeout The connection idle timeout duration

1239

* @return The updated HttpClientOptions object

1240

*/

1241

public HttpClientOptions setConnectionIdleTimeout(Duration connectionIdleTimeout);

1242

1243

/**

1244

* Gets the duration of time before an idle connection is closed.

1245

* @return The connection idle timeout duration

1246

*/

1247

public Duration getConnectionIdleTimeout();

1248

}

1249

```

1250

1251

### AsyncCloseable

1252

1253

Interface for asynchronous resource cleanup operations.

1254

1255

```java { .api }

1256

/**

1257

* Interface for close operations that are asynchronous.

1258

*/

1259

interface AsyncCloseable {

1260

/**

1261

* Begins the close operation. If one is in progress, will return that existing close operation.

1262

* @return A Mono representing the close operation

1263

*/

1264

Mono<Void> closeAsync();

1265

}

1266

```

1267

1268

### ServiceVersion

1269

1270

Interface for service version specification in Azure SDK clients.

1271

1272

```java { .api }

1273

/**

1274

* A generic interface for sending HTTP requests using the provided service version.

1275

*/

1276

interface ServiceVersion {

1277

/**

1278

* Gets the string representation of the ServiceVersion.

1279

* @return the string representation of the ServiceVersion

1280

*/

1281

String getVersion();

1282

}

1283

```

1284

1285

### UserAgentUtil

1286

1287

Utility for building user agent strings for Azure client libraries.

1288

1289

```java { .api }

1290

/**

1291

* Utility for building user agent string for Azure client libraries.

1292

*/

1293

class UserAgentUtil {

1294

/**

1295

* Default UserAgent header.

1296

*/

1297

public static final String DEFAULT_USER_AGENT_HEADER = "azsdk-java";

1298

1299

/**

1300

* Return user agent string for the given sdk name and version.

1301

* @param applicationId Name of the application

1302

* @param sdkName Name of the SDK

1303

* @param sdkVersion Version of the SDK

1304

* @param configuration The configuration to use to determine if platform info should be included

1305

* @return User agent string as specified in design guidelines

1306

*/

1307

public static String toUserAgentString(String applicationId, String sdkName, String sdkVersion,

1308

Configuration configuration);

1309

}

1310

```

1311

1312

### Base64 Utilities

1313

1314

Utilities for Base64 and Base64URL encoding and decoding operations.

1315

1316

```java { .api }

1317

/**

1318

* Utility type exposing Base64 encoding and decoding methods.

1319

*/

1320

class Base64Util {

1321

/**

1322

* Encodes a byte array to base64.

1323

* @param src the byte array to encode

1324

* @return the base64 encoded bytes

1325

*/

1326

public static byte[] encode(byte[] src);

1327

1328

/**

1329

* Encodes a byte array to base64 URL format.

1330

* @param src the byte array to encode

1331

* @return the base64 URL encoded bytes

1332

*/

1333

public static byte[] encodeURLWithoutPadding(byte[] src);

1334

1335

/**

1336

* Encodes a byte array to a base 64 string.

1337

* @param src the byte array to encode

1338

* @return the base64 encoded string

1339

*/

1340

public static String encodeToString(byte[] src);

1341

1342

/**

1343

* Decodes a base64 encoded byte array.

1344

* @param encoded the byte array to decode

1345

* @return the decoded byte array

1346

*/

1347

public static byte[] decode(byte[] encoded);

1348

1349

/**

1350

* Decodes a byte array in base64 URL format.

1351

* @param src the byte array to decode

1352

* @return the decoded byte array

1353

*/

1354

public static byte[] decodeURL(byte[] src);

1355

1356

/**

1357

* Decodes a base64 encoded string.

1358

* @param encoded the string to decode

1359

* @return the decoded byte array

1360

*/

1361

public static byte[] decodeString(String encoded);

1362

}

1363

1364

/**

1365

* Encodes and decodes using Base64 URL encoding.

1366

*/

1367

class Base64Url {

1368

/**

1369

* Creates a new Base64Url object with the specified encoded string.

1370

* @param string The encoded string

1371

*/

1372

public Base64Url(String string);

1373

1374

/**

1375

* Creates a new Base64Url object with the specified encoded bytes.

1376

* @param bytes The encoded bytes

1377

*/

1378

public Base64Url(byte[] bytes);

1379

1380

/**

1381

* Encodes a byte array into Base64Url encoded bytes.

1382

* @param bytes The byte array to encode

1383

* @return A new Base64Url instance

1384

*/

1385

public static Base64Url encode(byte[] bytes);

1386

1387

/**

1388

* Returns the underlying encoded byte array.

1389

* @return The underlying encoded byte array

1390

*/

1391

public byte[] encodedBytes();

1392

1393

/**

1394

* Decode the bytes and returns its value.

1395

* @return The decoded byte array

1396

*/

1397

public byte[] decodedBytes();

1398

1399

/**

1400

* Gets the string representation.

1401

* @return String representation of the encoded bytes

1402

*/

1403

@Override

1404

public String toString();

1405

}

1406

```

1407

1408

### Progress Tracking

1409

1410

Interfaces and classes for tracking progress of I/O operations.

1411

1412

```java { .api }

1413

/**

1414

* A ProgressListener is an interface that can be used to listen to the progress of I/O transfers.

1415

*/

1416

@FunctionalInterface

1417

interface ProgressListener {

1418

/**

1419

* The callback function invoked as progress is reported.

1420

* @param progress The total progress at the current point of time

1421

*/

1422

void handleProgress(long progress);

1423

}

1424

1425

/**

1426

* ProgressReporter offers a convenient way to add progress tracking to I/O operations.

1427

*/

1428

class ProgressReporter {

1429

/**

1430

* Creates a ProgressReporter that notifies ProgressListener.

1431

* @param progressListener The ProgressListener to be notified about progress

1432

* @return The ProgressReporter instance

1433

*/

1434

public static ProgressReporter withProgressListener(ProgressListener progressListener);

1435

1436

/**

1437

* Creates child ProgressReporter that can be used to track sub-progress.

1438

* @return The child ProgressReporter

1439

*/

1440

public ProgressReporter createChild();

1441

1442

/**

1443

* Resets progress to zero and notifies.

1444

*/

1445

public void reset();

1446

1447

/**

1448

* Accumulates the provided progress and notifies.

1449

* @param progress The number to be accumulated

1450

*/

1451

public void reportProgress(long progress);

1452

}

1453

```