or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

blob-client.mdcontainer-client.mdindex.mdmodels.mdoptions.mdsecurity.mdservice-client.mdspecialized-clients.mdstreaming.md

service-client.mddocs/

0

# Service Client Operations

1

2

Service clients provide the entry point for Azure Blob Storage operations, handling authentication, service-level configuration, and container management.

3

4

## BlobServiceClient

5

6

The synchronous client for Azure Blob Storage service operations.

7

8

### Creating a Service Client

9

10

```java

11

import com.azure.storage.blob.BlobServiceClient;

12

import com.azure.storage.blob.BlobServiceClientBuilder;

13

import com.azure.identity.DefaultAzureCredentialBuilder;

14

import com.azure.storage.common.StorageSharedKeyCredential;

15

16

// Using connection string (development/testing)

17

BlobServiceClient serviceClient = new BlobServiceClientBuilder()

18

.connectionString("DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;EndpointSuffix=core.windows.net")

19

.buildClient();

20

21

// Using Azure Identity (production recommended)

22

BlobServiceClient serviceClient = new BlobServiceClientBuilder()

23

.endpoint("https://myaccount.blob.core.windows.net")

24

.credential(new DefaultAzureCredentialBuilder().build())

25

.buildClient();

26

27

// Using shared key credential

28

StorageSharedKeyCredential credential = new StorageSharedKeyCredential("myaccount", "mykey");

29

BlobServiceClient serviceClient = new BlobServiceClientBuilder()

30

.endpoint("https://myaccount.blob.core.windows.net")

31

.credential(credential)

32

.buildClient();

33

34

// Using SAS token

35

BlobServiceClient serviceClient = new BlobServiceClientBuilder()

36

.endpoint("https://myaccount.blob.core.windows.net")

37

.sasToken("sv=2023-11-03&ss=b&srt=sco&sp=rwdlacupx&se=2024-01-01T00:00:00Z&st=2023-12-01T00:00:00Z&spr=https&sig=signature")

38

.buildClient();

39

```

40

41

### Container Management

42

43

```java

44

import com.azure.storage.blob.models.*;

45

import com.azure.core.http.rest.PagedIterable;

46

import com.azure.core.http.rest.Response;

47

import com.azure.core.util.Context;

48

49

// Create container

50

BlobContainerClient containerClient = serviceClient.createBlobContainer("mycontainer");

51

52

// Create container with options

53

Map<String, String> metadata = Map.of(

54

"environment", "production",

55

"team", "backend"

56

);

57

Response<BlobContainerClient> response = serviceClient.createBlobContainerWithResponse(

58

"mycontainer",

59

metadata,

60

PublicAccessType.BLOB,

61

Context.NONE

62

);

63

64

// Create container if not exists

65

BlobContainerClient containerClient = serviceClient.createBlobContainerIfNotExists("mycontainer");

66

67

// Get existing container client

68

BlobContainerClient containerClient = serviceClient.getBlobContainerClient("mycontainer");

69

70

// Delete container

71

serviceClient.deleteBlobContainer("mycontainer");

72

73

// Delete container if exists

74

boolean deleted = serviceClient.deleteBlobContainerIfExists("mycontainer");

75

76

// Undelete container (if soft delete is enabled)

77

BlobContainerClient restoredContainer = serviceClient.undeleteBlobContainer(

78

"mycontainer",

79

"01D64EAD4C6B7A00" // deletion version

80

);

81

```

82

83

### Listing Containers

84

85

```java

86

import com.azure.storage.blob.models.ListBlobContainersOptions;

87

import java.time.Duration;

88

89

// List all containers

90

PagedIterable<BlobContainerItem> containers = serviceClient.listBlobContainers();

91

for (BlobContainerItem container : containers) {

92

System.out.println("Container: " + container.getName());

93

System.out.println("Last Modified: " + container.getProperties().getLastModified());

94

System.out.println("Public Access: " + container.getProperties().getPublicAccess());

95

}

96

97

// List containers with filtering and options

98

ListBlobContainersOptions options = new ListBlobContainersOptions()

99

.setPrefix("test-")

100

.setDetails(new BlobContainerListDetails()

101

.setRetrieveDeleted(true)

102

.setRetrieveMetadata(true))

103

.setMaxResultsPerPage(50);

104

105

PagedIterable<BlobContainerItem> filteredContainers = serviceClient.listBlobContainers(

106

options,

107

Duration.ofSeconds(30)

108

);

109

110

for (BlobContainerItem container : filteredContainers) {

111

System.out.println("Container: " + container.getName());

112

System.out.println("Metadata: " + container.getMetadata());

113

System.out.println("Deleted: " + container.isDeleted());

114

}

115

```

116

117

### Service Properties

118

119

```java

120

import com.azure.storage.blob.models.*;

121

122

// Get service properties

123

BlobServiceProperties properties = serviceClient.getProperties();

124

System.out.println("Default service version: " + properties.getDefaultServiceVersion());

125

System.out.println("Hour metrics enabled: " + properties.getHourMetrics().isEnabled());

126

127

// Configure service properties

128

BlobServiceProperties newProperties = new BlobServiceProperties();

129

130

// Configure logging

131

BlobAnalyticsLogging logging = new BlobAnalyticsLogging()

132

.setVersion("1.0")

133

.setDeleteEnabled(true)

134

.setReadEnabled(true)

135

.setWriteEnabled(true)

136

.setRetentionPolicy(new BlobRetentionPolicy()

137

.setEnabled(true)

138

.setDays(30));

139

newProperties.setLogging(logging);

140

141

// Configure metrics

142

BlobMetrics hourMetrics = new BlobMetrics()

143

.setVersion("1.0")

144

.setEnabled(true)

145

.setIncludeApis(true)

146

.setRetentionPolicy(new BlobRetentionPolicy()

147

.setEnabled(true)

148

.setDays(7));

149

newProperties.setHourMetrics(hourMetrics);

150

151

// Configure CORS

152

List<BlobCorsRule> corsRules = List.of(

153

new BlobCorsRule()

154

.setAllowedOrigins("https://example.com")

155

.setAllowedMethods("GET,PUT,POST")

156

.setAllowedHeaders("x-ms-*,content-type")

157

.setExposedHeaders("x-ms-*")

158

.setMaxAgeInSeconds(3600)

159

);

160

newProperties.setCors(corsRules);

161

162

// Configure static website

163

BlobStaticWebsite staticWebsite = new BlobStaticWebsite()

164

.setEnabled(true)

165

.setIndexDocument("index.html")

166

.setErrorDocument404Path("error.html");

167

newProperties.setStaticWebsite(staticWebsite);

168

169

// Apply properties

170

serviceClient.setProperties(newProperties);

171

```

172

173

### Account Information

174

175

```java

176

// Get account information

177

StorageAccountInfo accountInfo = serviceClient.getAccountInfo();

178

System.out.println("Account kind: " + accountInfo.getAccountKind());

179

System.out.println("SKU name: " + accountInfo.getSkuName());

180

System.out.println("Hierarchical namespace: " + accountInfo.isHierarchicalNamespaceEnabled());

181

182

// Get service statistics (geo-replication info)

183

BlobServiceStatistics stats = serviceClient.getStatistics();

184

if (stats.getGeoReplication() != null) {

185

System.out.println("Geo-replication status: " + stats.getGeoReplication().getStatus());

186

System.out.println("Last sync time: " + stats.getGeoReplication().getLastSyncTime());

187

}

188

```

189

190

### Finding Blobs by Tags

191

192

```java

193

// Find blobs across all containers using tag queries

194

String tagQuery = "environment='production' AND team='backend'";

195

PagedIterable<TaggedBlobItem> taggedBlobs = serviceClient.findBlobsByTags(tagQuery);

196

197

for (TaggedBlobItem taggedBlob : taggedBlobs) {

198

System.out.println("Blob: " + taggedBlob.getName());

199

System.out.println("Container: " + taggedBlob.getContainerName());

200

System.out.println("Tags: " + taggedBlob.getTags().toMap());

201

}

202

203

// Find with pagination

204

FindBlobsOptions findOptions = new FindBlobsOptions(tagQuery)

205

.setMaxResultsPerPage(100);

206

207

PagedIterable<TaggedBlobItem> pagedResults = serviceClient.findBlobsByTags(findOptions, Duration.ofMinutes(1));

208

```

209

210

### User Delegation Keys

211

212

```java

213

import java.time.OffsetDateTime;

214

215

// Get user delegation key for SAS generation (Azure AD authentication only)

216

OffsetDateTime keyStart = OffsetDateTime.now();

217

OffsetDateTime keyExpiry = keyStart.plusDays(7);

218

219

try {

220

UserDelegationKey userDelegationKey = serviceClient.getUserDelegationKey(keyStart, keyExpiry);

221

222

System.out.println("Delegation key acquired");

223

System.out.println("Signed object ID: " + userDelegationKey.getSignedObjectId());

224

System.out.println("Valid until: " + userDelegationKey.getSignedExpiry());

225

226

// Use the key to generate SAS tokens

227

// (See security documentation for SAS generation details)

228

229

} catch (Exception ex) {

230

System.err.println("Failed to get user delegation key: " + ex.getMessage());

231

}

232

```

233

234

### Account SAS Generation

235

236

```java

237

import com.azure.storage.common.sas.*;

238

import java.time.OffsetDateTime;

239

240

// Generate account-level SAS token

241

OffsetDateTime expiryTime = OffsetDateTime.now().plusHours(24);

242

243

AccountSasSignatureValues accountSasValues = new AccountSasSignatureValues(

244

expiryTime,

245

AccountSasPermission.parse("rwdlacup"), // permissions

246

AccountSasService.parse("b"), // blob service

247

AccountSasResourceType.parse("sco") // service, container, object

248

)

249

.setStartTime(OffsetDateTime.now())

250

.setProtocol(SasProtocol.HTTPS_ONLY)

251

.setSasIpRange(SasIpRange.parse("168.1.5.60-168.1.5.70"));

252

253

String accountSas = serviceClient.generateAccountSas(accountSasValues);

254

System.out.println("Account SAS: " + accountSas);

255

```

256

257

## BlobServiceAsyncClient

258

259

The asynchronous client for Azure Blob Storage service operations using reactive programming.

260

261

### Creating an Async Service Client

262

263

```java

264

import com.azure.storage.blob.BlobServiceAsyncClient;

265

import reactor.core.publisher.Mono;

266

import reactor.core.publisher.Flux;

267

268

// Create async client

269

BlobServiceAsyncClient asyncServiceClient = new BlobServiceClientBuilder()

270

.connectionString("DefaultEndpointsProtocol=https;AccountName=myaccount;...")

271

.buildAsyncClient();

272

273

// All operations return Mono<T> or Flux<T>

274

```

275

276

### Async Container Operations

277

278

```java

279

// Create container asynchronously

280

Mono<BlobContainerAsyncClient> containerMono = asyncServiceClient.createBlobContainer("mycontainer");

281

282

// Chain operations

283

containerMono

284

.flatMap(container -> container.create())

285

.doOnSuccess(response -> System.out.println("Container created"))

286

.doOnError(error -> System.err.println("Creation failed: " + error.getMessage()))

287

.subscribe();

288

289

// List containers asynchronously

290

Flux<BlobContainerItem> containerFlux = asyncServiceClient.listBlobContainers();

291

containerFlux

292

.take(10) // Limit to first 10 containers

293

.doOnNext(container -> System.out.println("Container: " + container.getName()))

294

.doOnComplete(() -> System.out.println("Listing complete"))

295

.subscribe();

296

```

297

298

### Async Service Configuration

299

300

```java

301

// Get properties asynchronously

302

Mono<BlobServiceProperties> propertiesMono = asyncServiceClient.getProperties();

303

304

propertiesMono

305

.doOnNext(props -> {

306

System.out.println("Default version: " + props.getDefaultServiceVersion());

307

System.out.println("Static website enabled: " +

308

(props.getStaticWebsite() != null && props.getStaticWebsite().isEnabled()));

309

})

310

.subscribe();

311

312

// Update properties

313

BlobServiceProperties newProps = new BlobServiceProperties()

314

.setDefaultServiceVersion("2023-11-03");

315

316

Mono<Void> updateMono = asyncServiceClient.setProperties(newProps);

317

updateMono

318

.doOnSuccess(v -> System.out.println("Properties updated"))

319

.doOnError(ex -> System.err.println("Update failed: " + ex.getMessage()))

320

.subscribe();

321

```

322

323

### Error Handling with Async Client

324

325

```java

326

import com.azure.storage.blob.models.BlobStorageException;

327

328

// Handle errors in reactive chains

329

asyncServiceClient.createBlobContainer("invalid/container/name")

330

.doOnSuccess(container -> System.out.println("Container created"))

331

.onErrorResume(BlobStorageException.class, ex -> {

332

System.err.println("Storage error: " + ex.getErrorCode());

333

System.err.println("Status: " + ex.getStatusCode());

334

return Mono.empty(); // Continue with empty result

335

})

336

.onErrorResume(Exception.class, ex -> {

337

System.err.println("General error: " + ex.getMessage());

338

return Mono.error(ex); // Re-throw other exceptions

339

})

340

.subscribe();

341

342

// Blocking operations (use sparingly)

343

try {

344

BlobContainerAsyncClient container = asyncServiceClient

345

.createBlobContainer("mycontainer")

346

.block(Duration.ofSeconds(30));

347

System.out.println("Container created: " + container.getBlobContainerName());

348

} catch (Exception ex) {

349

System.err.println("Operation failed: " + ex.getMessage());

350

}

351

```

352

353

## Client Configuration

354

355

### Custom HTTP Configuration

356

357

```java

358

import com.azure.core.http.HttpClient;

359

import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;

360

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

361

import java.time.Duration;

362

363

// Configure HTTP client

364

HttpClient httpClient = new NettyAsyncHttpClientBuilder()

365

.connectionTimeout(Duration.ofSeconds(60))

366

.responseTimeout(Duration.ofSeconds(120))

367

.maxIdleTime(Duration.ofSeconds(60))

368

.build();

369

370

// Configure retry policy

371

RetryPolicy retryPolicy = new RetryPolicy("fixed", 3);

372

373

// Build service client with custom configuration

374

BlobServiceClient serviceClient = new BlobServiceClientBuilder()

375

.endpoint("https://myaccount.blob.core.windows.net")

376

.credential(new DefaultAzureCredentialBuilder().build())

377

.httpClient(httpClient)

378

.retryPolicy(retryPolicy)

379

.addPolicy(new UserAgentPolicy("MyApp/1.0"))

380

.serviceVersion(BlobServiceVersion.V2023_11_03)

381

.buildClient();

382

```

383

384

### Customer-Provided Encryption

385

386

```java

387

import com.azure.storage.blob.models.CustomerProvidedKey;

388

import com.azure.storage.blob.models.EncryptionAlgorithmType;

389

390

// Configure customer-provided encryption key

391

CustomerProvidedKey cpk = new CustomerProvidedKey("myEncryptionKey")

392

.setEncryptionAlgorithm(EncryptionAlgorithmType.AES256);

393

394

BlobServiceClient serviceClient = new BlobServiceClientBuilder()

395

.connectionString("DefaultEndpointsProtocol=https;AccountName=myaccount;...")

396

.customerProvidedKey(cpk)

397

.buildClient();

398

399

// All operations will use the provided encryption key

400

```

401

402

### Encryption Scope

403

404

```java

405

// Configure encryption scope

406

BlobServiceClient serviceClient = new BlobServiceClientBuilder()

407

.connectionString("DefaultEndpointsProtocol=https;AccountName=myaccount;...")

408

.encryptionScope("myencryptionscope")

409

.buildClient();

410

411

// All blobs created through this client will use the encryption scope

412

```

413

414

## Service Client Properties

415

416

### Key Properties

417

418

```java

419

// Get service client properties

420

String accountUrl = serviceClient.getAccountUrl();

421

String accountName = serviceClient.getAccountName();

422

BlobServiceVersion serviceVersion = serviceClient.getServiceVersion();

423

424

System.out.println("Account URL: " + accountUrl);

425

System.out.println("Account Name: " + accountName);

426

System.out.println("Service Version: " + serviceVersion.getVersion());

427

428

// Access HTTP pipeline for advanced scenarios

429

HttpPipeline pipeline = serviceClient.getHttpPipeline();

430

```

431

432

## Constants

433

434

```java

435

// Important service-level constants

436

public static final String ROOT_CONTAINER_NAME = "$root";

437

public static final String STATIC_WEBSITE_CONTAINER_NAME = "$web";

438

public static final String LOG_CONTAINER_NAME = "$logs";

439

440

// Use these for special containers

441

BlobContainerClient rootContainer = serviceClient.getBlobContainerClient(BlobContainerClient.ROOT_CONTAINER_NAME);

442

BlobContainerClient webContainer = serviceClient.getBlobContainerClient(BlobContainerClient.STATIC_WEBSITE_CONTAINER_NAME);

443

```

444

445

## Related Documentation

446

447

- [← Back to Overview](index.md)

448

- [Container Management →](container-client.md)

449

- [Blob Operations →](blob-client.md)

450

- [Security & Authentication →](security.md)

451

- [Configuration Options →](options.md)