or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

actors.mdcollections.mdcore-api.mdexceptions.mdindex.mdjson-api.mdlogging.mdutilities.md

utilities.mddocs/

0

# Utility Classes

1

2

Apache ActiveMQ Artemis Commons provides a comprehensive set of utility classes for threading, pooling, validation, environment access, and general-purpose operations used throughout the Artemis ecosystem.

3

4

## Threading and Concurrency

5

6

### Thread Factory

7

8

Custom thread factory for creating properly named and configured threads.

9

10

```java { .api }

11

class ActiveMQThreadFactory implements ThreadFactory {

12

// Constructors

13

ActiveMQThreadFactory(String groupName, boolean daemon, ClassLoader tccl);

14

ActiveMQThreadFactory(String groupName, String prefix, boolean daemon, ClassLoader tccl);

15

16

// ThreadFactory implementation

17

Thread newThread(Runnable command);

18

19

// Thread management

20

boolean join(int timeout, TimeUnit timeUnit);

21

22

// Factory method

23

static ActiveMQThreadFactory defaultThreadFactory(String callerClassName);

24

}

25

```

26

27

#### Usage Examples

28

29

```java

30

// Create thread factory for background tasks

31

ActiveMQThreadFactory factory = new ActiveMQThreadFactory(

32

"MessageProcessor", // group name

33

true, // daemon threads

34

getClass().getClassLoader()

35

);

36

37

// Create threads with proper naming

38

Thread worker = factory.newThread(() -> {

39

// Background message processing

40

processMessages();

41

});

42

43

// Use default factory

44

ActiveMQThreadFactory defaultFactory =

45

ActiveMQThreadFactory.defaultThreadFactory("MyComponent");

46

47

// Wait for all threads to finish

48

boolean finished = factory.join(30, TimeUnit.SECONDS);

49

```

50

51

### Thread Pool Executor

52

53

Enhanced thread pool executor with monitoring capabilities.

54

55

```java { .api }

56

class ActiveMQThreadPoolExecutor extends ThreadPoolExecutor {

57

// Enhanced ThreadPoolExecutor for ActiveMQ with monitoring

58

// (Specific constructor signatures depend on implementation)

59

}

60

```

61

62

### Executor Factory

63

64

```java { .api }

65

interface ExecutorFactory {

66

// Factory interface for creating executors

67

Executor getExecutor();

68

}

69

```

70

71

## Data Utilities

72

73

### Byte Operations

74

75

Utilities for byte array manipulation and conversion.

76

77

```java { .api }

78

class ByteUtil {

79

// Hex string conversion

80

static byte[] hexStringToByteArray(String hexString);

81

static String bytesToHex(byte[] bytes);

82

83

// Additional byte manipulation methods

84

// (Specific methods depend on implementation)

85

}

86

```

87

88

#### Usage Examples

89

90

```java

91

// Convert hex string to bytes

92

byte[] data = ByteUtil.hexStringToByteArray("48656C6C6F"); // "Hello"

93

94

// Convert bytes back to hex

95

String hex = ByteUtil.bytesToHex(data); // "48656C6C6F"

96

97

// Useful for debugging binary data

98

String debugHex = ByteUtil.bytesToHex(messageBytes);

99

System.out.println("Message bytes: " + debugHex);

100

```

101

102

### Boolean Utilities

103

104

```java { .api }

105

class BooleanUtil {

106

// Boolean conversion and utility methods

107

// (Specific methods depend on implementation)

108

}

109

```

110

111

### Base64 Encoding

112

113

Base64 encoding and decoding utilities.

114

115

```java { .api }

116

class Base64 {

117

// Base64 encoding/decoding operations

118

static String encode(byte[] data);

119

static byte[] decode(String encoded);

120

// Additional Base64 methods

121

}

122

```

123

124

### Address Utilities

125

126

Utilities for working with ActiveMQ addresses and destination names.

127

128

```java { .api }

129

class CompositeAddress {

130

// Utilities for fully-qualified queue names (address::queue format)

131

static String extractQueueName(String compositeAddress);

132

static String extractAddressName(String compositeAddress);

133

static String toFullyQualified(String address, String queue);

134

// Additional composite address methods

135

}

136

137

class DestinationUtil {

138

// Destination name manipulation utilities

139

// (Specific methods depend on implementation)

140

}

141

```

142

143

#### Usage Examples

144

145

```java

146

// Work with composite addresses

147

String fullAddress = "orders::priority-queue";

148

String address = CompositeAddress.extractAddressName(fullAddress); // "orders"

149

String queue = CompositeAddress.extractQueueName(fullAddress); // "priority-queue"

150

151

// Create composite address

152

String composite = CompositeAddress.toFullyQualified("notifications", "email-queue");

153

// Result: "notifications::email-queue"

154

```

155

156

### Data Constants

157

158

```java { .api }

159

class DataConstants {

160

// Size constants for different data types

161

static final int SIZE_BOOLEAN = 1;

162

static final int SIZE_BYTE = 1;

163

static final int SIZE_SHORT = 2;

164

static final int SIZE_INT = 4;

165

static final int SIZE_LONG = 8;

166

static final int SIZE_FLOAT = 4;

167

static final int SIZE_DOUBLE = 8;

168

169

// Additional data type markers and constants

170

}

171

```

172

173

## Pooling and Memory Management

174

175

### Abstract Pool Base Classes

176

177

```java { .api }

178

abstract class AbstractPool<K, V> {

179

// Base class for object pooling implementations

180

abstract V get(K key);

181

abstract void put(K key, V value);

182

abstract void clear();

183

}

184

185

abstract class AbstractByteBufPool<T> extends AbstractPool<ByteBuf, T> {

186

// Base class for ByteBuf-based object pools

187

}

188

```

189

190

### Pool Interface and Implementation

191

192

```java { .api }

193

interface Pool<T> {

194

// Generic pool interface

195

T get();

196

void put(T item);

197

void clear();

198

int size();

199

}

200

201

class MpscPool<T> implements Pool<T> {

202

// Multi-producer, single-consumer pool implementation

203

MpscPool(int capacity, Supplier<T> supplier);

204

205

T get();

206

void put(T item);

207

void clear();

208

int size();

209

}

210

```

211

212

#### Usage Examples

213

214

```java

215

// Create a pool for expensive objects

216

MpscPool<StringBuilder> stringBuilderPool = new MpscPool<>(

217

10, // capacity

218

() -> new StringBuilder(256) // supplier

219

);

220

221

// Use pooled objects

222

StringBuilder sb = stringBuilderPool.get();

223

try {

224

sb.append("Message: ").append(data);

225

String result = sb.toString();

226

// Use result

227

} finally {

228

sb.setLength(0); // reset

229

stringBuilderPool.put(sb); // return to pool

230

}

231

```

232

233

## Reference Counting and Lifecycle

234

235

### Reference Counter

236

237

```java { .api }

238

interface ReferenceCounter {

239

// Reference counting for resource management

240

int increment();

241

int decrement();

242

int getCount();

243

}

244

```

245

246

### Enhanced Closeable

247

248

```java { .api }

249

interface ArtemisCloseable extends AutoCloseable {

250

// Enhanced closeable interface for Artemis resources

251

void close() throws ActiveMQException;

252

boolean isClosed();

253

}

254

```

255

256

#### Usage Examples

257

258

```java

259

// Resource with reference counting

260

class ManagedResource implements ReferenceCounter, ArtemisCloseable {

261

private final ReferenceCounter refCounter = /* implementation */;

262

263

public void use() {

264

refCounter.increment();

265

try {

266

// Use resource

267

} finally {

268

if (refCounter.decrement() == 0) {

269

// Last reference, cleanup

270

cleanup();

271

}

272

}

273

}

274

}

275

276

// Try-with-resources pattern

277

try (ArtemisCloseable resource = createManagedResource()) {

278

// Use resource

279

resource.performOperation();

280

} // Automatically closed

281

```

282

283

## Timing and Synchronization

284

285

### UUID Timer

286

287

```java { .api }

288

class UUIDTimer {

289

// Timer utilities for UUID generation

290

// (Specific methods depend on implementation)

291

}

292

```

293

294

### Latch Implementations

295

296

```java { .api }

297

class AutomaticLatch {

298

// Self-managing latch implementation

299

AutomaticLatch(int count);

300

301

void await() throws InterruptedException;

302

void await(long timeout, TimeUnit unit) throws InterruptedException;

303

void countDown();

304

int getCount();

305

}

306

307

class ReusableLatch {

308

// Reusable countdown latch implementation

309

ReusableLatch(int initialCount);

310

311

void await() throws InterruptedException;

312

void await(long timeout, TimeUnit unit) throws InterruptedException;

313

void countDown();

314

void reset(int count);

315

int getCount();

316

}

317

```

318

319

#### Usage Examples

320

321

```java

322

// Coordinate multiple operations

323

AutomaticLatch completionLatch = new AutomaticLatch(3);

324

325

// Start three async operations

326

for (int i = 0; i < 3; i++) {

327

executor.submit(() -> {

328

try {

329

performOperation();

330

} finally {

331

completionLatch.countDown();

332

}

333

});

334

}

335

336

// Wait for all operations to complete

337

completionLatch.await(30, TimeUnit.SECONDS);

338

339

// Reusable latch for repeated coordination

340

ReusableLatch batchLatch = new ReusableLatch(10);

341

while (hasMoreBatches()) {

342

processBatch();

343

batchLatch.countDown();

344

345

if (batchLatch.getCount() == 0) {

346

// Batch complete, reset for next batch

347

batchLatch.reset(10);

348

}

349

}

350

```

351

352

## Validation and Preconditions

353

354

### Precondition Checking

355

356

```java { .api }

357

class Preconditions {

358

// Validation utilities for checking preconditions

359

static void checkArgument(boolean condition, String message);

360

static void checkNotNull(Object reference, String message);

361

static void checkState(boolean condition, String message);

362

363

// Additional validation methods

364

static void checkElementIndex(int index, int size, String message);

365

static void checkPositionIndex(int index, int size, String message);

366

}

367

```

368

369

#### Usage Examples

370

371

```java

372

public void processQueue(String queueName, int maxMessages) {

373

Preconditions.checkNotNull(queueName, "Queue name cannot be null");

374

Preconditions.checkArgument(maxMessages > 0, "Max messages must be positive");

375

Preconditions.checkState(isConnected(), "Must be connected to process queue");

376

377

// Proceed with processing

378

doProcessQueue(queueName, maxMessages);

379

}

380

381

public Object getElement(List<Object> list, int index) {

382

Preconditions.checkNotNull(list, "List cannot be null");

383

Preconditions.checkElementIndex(index, list.size(), "Invalid index");

384

385

return list.get(index);

386

}

387

```

388

389

## Environment and Configuration

390

391

### Environment Access

392

393

```java { .api }

394

class Env {

395

// Environment and system property utilities

396

static String getProperty(String key);

397

static String getProperty(String key, String defaultValue);

398

static boolean getBooleanProperty(String key, boolean defaultValue);

399

static int getIntProperty(String key, int defaultValue);

400

static long getLongProperty(String key, long defaultValue);

401

402

// Environment variable access

403

static String getEnv(String name);

404

static String getEnv(String name, String defaultValue);

405

}

406

```

407

408

#### Usage Examples

409

410

```java

411

// Read configuration from system properties

412

int poolSize = Env.getIntProperty("artemis.pool.size", 10);

413

boolean debugMode = Env.getBooleanProperty("artemis.debug", false);

414

String logLevel = Env.getProperty("artemis.log.level", "INFO");

415

416

// Read from environment variables

417

String dataDir = Env.getEnv("ARTEMIS_DATA_DIR", "/var/lib/artemis");

418

String configFile = Env.getEnv("ARTEMIS_CONFIG", "artemis.xml");

419

420

// Use configuration

421

if (debugMode) {

422

logger.info("Debug mode enabled, pool size: " + poolSize);

423

}

424

```

425

426

### String Encoding

427

428

```java { .api }

429

class DefaultSensitiveStringCodec {

430

// Default implementation for encoding/decoding sensitive strings

431

String encode(String plainText) throws Exception;

432

String decode(String encodedText) throws Exception;

433

}

434

```

435

436

### Class Loading

437

438

```java { .api }

439

class ClassloadingUtil {

440

// Class loading utilities

441

static Class<?> loadClass(String className, ClassLoader classLoader);

442

static <T> T newInstance(String className, ClassLoader classLoader, Class<T> type);

443

444

// Additional class loading methods

445

}

446

```

447

448

### File Operations

449

450

```java { .api }

451

class FileUtil {

452

// File manipulation utilities

453

static void deleteDirectory(File directory) throws IOException;

454

static void copyDirectory(File source, File target) throws IOException;

455

static boolean createDirectories(File directory);

456

static long getFileSize(File file);

457

static byte[] readFileBytes(File file) throws IOException;

458

static void writeFileBytes(File file, byte[] data) throws IOException;

459

460

// Additional file operations

461

}

462

```

463

464

### Time Utilities

465

466

```java { .api }

467

class TimeUtils {

468

// Time and duration utilities

469

static long currentTimeMillis();

470

static long nanoTime();

471

static String formatDuration(long durationMs);

472

static long parseDuration(String duration);

473

static boolean isExpired(long timestamp, long timeoutMs);

474

475

// Additional time operations

476

}

477

```

478

479

### UTF-8 Encoding

480

481

```java { .api }

482

class UTF8Util {

483

// UTF-8 encoding and decoding utilities

484

static byte[] encode(String string);

485

static String decode(byte[] bytes);

486

static int calculateEncodedLength(String string);

487

static boolean isValidUTF8(byte[] bytes);

488

489

// Additional UTF-8 methods

490

}

491

```

492

493

### UUID Generation

494

495

```java { .api }

496

class UUID {

497

// UUID representation and operations

498

UUID(long mostSigBits, long leastSigBits);

499

static UUID randomUUID();

500

static UUID fromString(String name);

501

502

long getMostSignificantBits();

503

long getLeastSignificantBits();

504

String toString();

505

}

506

507

class UUIDGenerator {

508

// UUID generation utilities

509

static UUID generateTimeBasedUUID();

510

static UUID generateRandomUUID();

511

static String generateUUIDString();

512

513

// Additional UUID generation methods

514

}

515

```

516

517

### String Utilities

518

519

```java { .api }

520

class StringEscapeUtils {

521

// String escaping and unescaping utilities

522

static String escapeJava(String input);

523

static String unescapeJava(String input);

524

static String escapeXml(String input);

525

static String unescapeXml(String input);

526

static String escapeHtml(String input);

527

static String unescapeHtml(String input);

528

529

// Additional string escape methods

530

}

531

```

532

533

### Type-Safe Properties

534

535

```java { .api }

536

class TypedProperties implements Map<SimpleString, Object> {

537

// Type-safe property storage

538

TypedProperties();

539

TypedProperties(TypedProperties other);

540

541

// Type-safe getters

542

String getStringProperty(SimpleString key);

543

Integer getIntProperty(SimpleString key);

544

Long getLongProperty(SimpleString key);

545

Boolean getBooleanProperty(SimpleString key);

546

Double getDoubleProperty(SimpleString key);

547

548

// Type-safe setters

549

TypedProperties setStringProperty(SimpleString key, String value);

550

TypedProperties setIntProperty(SimpleString key, int value);

551

TypedProperties setLongProperty(SimpleString key, long value);

552

TypedProperties setBooleanProperty(SimpleString key, boolean value);

553

TypedProperties setDoubleProperty(SimpleString key, double value);

554

555

// Property manipulation

556

boolean containsProperty(SimpleString key);

557

Object removeProperty(SimpleString key);

558

Set<SimpleString> getPropertyNames();

559

int getEncodeSize();

560

561

// Map interface methods inherited from Map<SimpleString, Object>

562

}

563

```

564

565

### Concurrency Utilities

566

567

```java { .api }

568

class ConcurrentUtil {

569

// Concurrency utilities and helpers

570

static void parkNanos(long nanos);

571

static void yield();

572

static void onSpinWait();

573

574

// Additional concurrency helpers

575

}

576

```

577

578

## Usage Patterns

579

580

### Resource Management Pattern

581

582

```java

583

// Combine multiple utilities for robust resource management

584

public class ResourceManager implements ArtemisCloseable {

585

private final ActiveMQThreadFactory threadFactory;

586

private final ReferenceCounter refCounter;

587

private final ReusableLatch operationLatch;

588

589

public ResourceManager(String name) {

590

this.threadFactory = new ActiveMQThreadFactory(name, true, getClassLoader());

591

this.refCounter = createReferenceCounter();

592

this.operationLatch = new ReusableLatch(1);

593

594

Preconditions.checkNotNull(name, "Resource name cannot be null");

595

}

596

597

public void performOperation() throws ActiveMQException {

598

Preconditions.checkState(!isClosed(), "Resource is closed");

599

600

refCounter.increment();

601

try {

602

Thread worker = threadFactory.newThread(this::doWork);

603

worker.start();

604

operationLatch.await(30, TimeUnit.SECONDS);

605

} finally {

606

if (refCounter.decrement() == 0) {

607

cleanup();

608

}

609

}

610

}

611

}

612

```

613

614

### Configuration and Environment Pattern

615

616

```java

617

// Use environment utilities for flexible configuration

618

public class ConfigurableProcessor {

619

private final int batchSize;

620

private final long timeoutMs;

621

private final boolean useCompression;

622

private final String workDir;

623

624

public ConfigurableProcessor() {

625

// Load configuration with sensible defaults

626

this.batchSize = Env.getIntProperty("processor.batch.size", 100);

627

this.timeoutMs = Env.getLongProperty("processor.timeout.ms", 30000);

628

this.useCompression = Env.getBooleanProperty("processor.compression", false);

629

this.workDir = Env.getEnv("PROCESSOR_WORK_DIR", "/tmp/processor");

630

631

// Validate configuration

632

Preconditions.checkArgument(batchSize > 0, "Batch size must be positive");

633

Preconditions.checkArgument(timeoutMs > 0, "Timeout must be positive");

634

Preconditions.checkNotNull(workDir, "Work directory must be specified");

635

}

636

}

637

```