or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

constants-configuration.mdcore-functionality.mdcrypto-utilities.mdenums-types.mdindex.mdprofile-management.mdreflection-utilities.mdutility-functions.md

utility-functions.mddocs/

0

# Utility Functions

1

2

This document covers the extensive utility functionality in the `org.keycloak.common.util` package that provides helper classes for encoding, networking, I/O operations, collections, and various common programming tasks.

3

4

## Encoding and Data Conversion Utilities

5

6

### Base64 Encoding

7

8

The `Base64` class provides comprehensive Base64 encoding and decoding functionality.

9

10

```java { .api }

11

public class Base64 {

12

// Basic encoding methods

13

public static String encodeBytes(byte[] source);

14

public static String encodeBytes(byte[] source, int options);

15

public static String encodeBytes(byte[] source, int off, int len);

16

public static String encodeBytes(byte[] source, int off, int len, int options);

17

18

// Object serialization encoding

19

public static String encodeObject(Serializable serializableObject);

20

public static String encodeObject(Serializable serializableObject, int options);

21

22

// Buffer-based encoding

23

public static void encode(ByteBuffer raw, ByteBuffer encoded);

24

public static void encode(ByteBuffer raw, CharBuffer encoded);

25

26

// Nested stream classes

27

public static class InputStream extends FilterInputStream {

28

public InputStream(java.io.InputStream in);

29

public InputStream(java.io.InputStream in, int options);

30

}

31

32

public static class OutputStream extends FilterOutputStream {

33

public OutputStream(java.io.OutputStream out);

34

public OutputStream(java.io.OutputStream out, int options);

35

}

36

}

37

```

38

39

### Base64Url Encoding

40

41

URL-safe Base64 encoding utilities for web applications.

42

43

```java { .api }

44

public class Base64Url {

45

public static String encode(byte[] bytes);

46

public static byte[] decode(String str);

47

public static String encodeToString(byte[] bytes);

48

}

49

```

50

51

### Usage Examples

52

53

```java

54

// Basic Base64 encoding

55

byte[] data = "Hello, World!".getBytes();

56

String encoded = Base64.encodeBytes(data);

57

58

// Serialize and encode object

59

Serializable obj = new MySerializableObject();

60

String encodedObj = Base64.encodeObject(obj);

61

62

// URL-safe encoding for web use

63

String urlSafe = Base64Url.encode(data);

64

byte[] decoded = Base64Url.decode(urlSafe);

65

66

// Stream-based encoding

67

try (Base64.OutputStream b64Out = new Base64.OutputStream(fileOut)) {

68

b64Out.write(data);

69

}

70

```

71

72

## Collection Utilities

73

74

### MultivaluedMap Interface

75

76

A map interface that supports multiple values per key, commonly used in HTTP headers and form parameters.

77

78

```java { .api }

79

public interface MultivaluedMap<K, V> extends Map<K, List<V>> {

80

// Single value operations

81

void putSingle(K key, V value);

82

V getFirst(K key);

83

V getFirstOrDefault(K key, V defaultValue);

84

85

// Multiple value operations

86

void add(K key, V value);

87

void addFirst(K key, V value);

88

void addAll(K key, V... newValues);

89

void addAll(K key, List<V> valueList);

90

void addMultiple(K key, Collection<V> values);

91

92

// List operations

93

List<V> getList(K key);

94

List<V> createListInstance();

95

96

// Bulk operations

97

void addAll(MultivaluedMap<K, V> other);

98

99

// Comparison

100

boolean equalsIgnoreValueOrder(MultivaluedMap<K, V> omap);

101

}

102

```

103

104

### MultivaluedHashMap Implementation

105

106

```java { .api }

107

public class MultivaluedHashMap<K, V> extends HashMap<K, List<V>> implements MultivaluedMap<K, V> {

108

public MultivaluedHashMap();

109

public MultivaluedHashMap(Map<K, List<V>> map);

110

111

// All MultivaluedMap interface methods implemented

112

}

113

```

114

115

### ConcurrentMultivaluedHashMap Implementation

116

117

Thread-safe implementation of MultivaluedMap.

118

119

```java { .api }

120

public class ConcurrentMultivaluedHashMap<K, V> extends ConcurrentHashMap<K, List<V>>

121

implements MultivaluedMap<K, V> {

122

public ConcurrentMultivaluedHashMap();

123

124

// Thread-safe implementations of all MultivaluedMap methods

125

}

126

```

127

128

### Usage Examples

129

130

```java

131

// Create and populate multivalued map

132

MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();

133

headers.putSingle("Content-Type", "application/json");

134

headers.add("Accept", "application/json");

135

headers.add("Accept", "text/plain");

136

137

// Retrieve values

138

String contentType = headers.getFirst("Content-Type");

139

List<String> acceptValues = headers.getList("Accept");

140

141

// Thread-safe version for concurrent access

142

MultivaluedMap<String, String> concurrent = new ConcurrentMultivaluedHashMap<>();

143

```

144

145

## Network and URI Utilities

146

147

### KeycloakUriBuilder

148

149

URI builder specifically designed for Keycloak's URL patterns.

150

151

```java { .api }

152

public class KeycloakUriBuilder {

153

public static KeycloakUriBuilder fromUri(String uriTemplate);

154

public static KeycloakUriBuilder fromUri(URI uri);

155

156

// Path building methods

157

public KeycloakUriBuilder path(String segment);

158

public KeycloakUriBuilder queryParam(String name, Object... values);

159

160

// Build final URI

161

public URI build(Object... values);

162

public String buildAsString(Object... values);

163

}

164

```

165

166

### UriUtils

167

168

General URI manipulation utilities.

169

170

```java { .api }

171

public class UriUtils {

172

public static String formatUrl(String url, Object... args);

173

public static MultivaluedMap<String, String> parseQueryString(String query);

174

public static String encodeQueryString(MultivaluedMap<String, String> params);

175

}

176

```

177

178

### NetworkUtils

179

180

Network-related utilities for IP addresses and hostnames.

181

182

```java { .api }

183

public class NetworkUtils {

184

public static boolean isValidIpAddress(String ip);

185

public static boolean isLocalhost(String host);

186

public static String getLocalHostname();

187

public static List<String> getLocalAddresses();

188

}

189

```

190

191

### Usage Examples

192

193

```java

194

// Build Keycloak URLs

195

KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri("/auth/realms/{realm}/protocol/openid-connect/token");

196

URI tokenUri = builder.build("master");

197

198

// Parse query parameters

199

String query = "client_id=my-client&response_type=code";

200

MultivaluedMap<String, String> params = UriUtils.parseQueryString(query);

201

String clientId = params.getFirst("client_id");

202

203

// Network utilities

204

boolean isLocal = NetworkUtils.isLocalhost("127.0.0.1");

205

String hostname = NetworkUtils.getLocalHostname();

206

```

207

208

## I/O and File Utilities

209

210

### IoUtils

211

212

Input/output stream utilities.

213

214

```java { .api }

215

public class IoUtils {

216

public static byte[] readBytes(InputStream is) throws IOException;

217

public static String readString(InputStream is, Charset charset) throws IOException;

218

public static void copy(InputStream input, OutputStream output) throws IOException;

219

public static void closeQuietly(Closeable closeable);

220

}

221

```

222

223

### FindFile

224

225

File finding and resource loading utilities.

226

227

```java { .api }

228

public class FindFile {

229

public static InputStream findFile(String fileName);

230

public static URL findFileUrl(String fileName);

231

public static File findFileFromClasspath(String fileName);

232

}

233

```

234

235

### Usage Examples

236

237

```java

238

// Read file contents

239

try (InputStream is = FindFile.findFile("config.properties")) {

240

byte[] content = IoUtils.readBytes(is);

241

String text = IoUtils.readString(is, StandardCharsets.UTF_8);

242

}

243

244

// Safe resource closing

245

Closeable resource = openResource();

246

IoUtils.closeQuietly(resource); // No exception thrown

247

```

248

249

## Security and Cryptographic Utilities

250

251

### KeyUtils

252

253

Key generation and manipulation utilities.

254

255

```java { .api }

256

public class KeyUtils {

257

public static KeyPair generateRsaKeyPair(int keySize);

258

public static PublicKey extractPublicKey(PrivateKey privateKey);

259

public static String getKeyId(Key key);

260

}

261

```

262

263

### CertificateUtils

264

265

Certificate processing utilities.

266

267

```java { .api }

268

public class CertificateUtils {

269

public static X509Certificate parseCertificate(byte[] certificateBytes);

270

public static byte[] getCertificateBytes(X509Certificate certificate);

271

public static String getCertificatePem(X509Certificate certificate);

272

}

273

```

274

275

### PemUtils

276

277

PEM format processing utilities.

278

279

```java { .api }

280

public class PemUtils {

281

public static PrivateKey decodePrivateKey(String pem);

282

public static PublicKey decodePublicKey(String pem);

283

public static X509Certificate decodeCertificate(String pem);

284

285

public static String encode(PrivateKey key);

286

public static String encode(PublicKey key);

287

public static String encode(X509Certificate certificate);

288

}

289

```

290

291

### Usage Examples

292

293

```java

294

// Generate key pair

295

KeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);

296

String keyId = KeyUtils.getKeyId(keyPair.getPublic());

297

298

// Process PEM certificates

299

String pemCert = "-----BEGIN CERTIFICATE-----\n...";

300

X509Certificate cert = PemUtils.decodeCertificate(pemCert);

301

String encodedCert = PemUtils.encode(cert);

302

```

303

304

## Time and Environment Utilities

305

306

### Time

307

308

Time manipulation and formatting utilities.

309

310

```java { .api }

311

public class Time {

312

public static int currentTime();

313

public static long currentTimeMillis();

314

public static String formatTime(long timeMillis, String pattern);

315

public static Date parseTime(String timeString, String pattern);

316

}

317

```

318

319

### Environment

320

321

Environment and system information utilities.

322

323

```java { .api }

324

public class Environment {

325

public static String getProperty(String key);

326

public static String getProperty(String key, String defaultValue);

327

public static boolean isWindows();

328

public static boolean isLinux();

329

public static boolean isMac();

330

}

331

```

332

333

### EnvUtil

334

335

Environment variable processing utilities.

336

337

```java { .api }

338

public class EnvUtil {

339

public static String replace(String value);

340

public static Properties replaceProperties(Properties properties);

341

public static Map<String, String> getEnvironmentVariables();

342

}

343

```

344

345

### Usage Examples

346

347

```java

348

// Time operations

349

int currentTime = Time.currentTime();

350

String formatted = Time.formatTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");

351

352

// Environment detection

353

if (Environment.isWindows()) {

354

// Windows-specific logic

355

}

356

357

// Environment variable substitution

358

String config = "Database URL: ${DB_URL}";

359

String resolved = EnvUtil.replace(config);

360

```

361

362

## String and Text Processing Utilities

363

364

### StringPropertyReplacer

365

366

Property placeholder replacement in strings.

367

368

```java { .api }

369

public class StringPropertyReplacer {

370

public static String replaceProperties(String string);

371

public static String replaceProperties(String string, Properties properties);

372

public static String replaceProperties(String string, Map<String, String> properties);

373

}

374

```

375

376

### HtmlUtils

377

378

HTML content processing utilities.

379

380

```java { .api }

381

public class HtmlUtils {

382

public static String escapeAttribute(String value);

383

public static String escapeHtml(String value);

384

public static String unescapeHtml(String value);

385

}

386

```

387

388

### Usage Examples

389

390

```java

391

// Property replacement

392

String template = "Hello ${user.name}, welcome to ${app.name}!";

393

Properties props = new Properties();

394

props.setProperty("user.name", "John");

395

props.setProperty("app.name", "Keycloak");

396

String result = StringPropertyReplacer.replaceProperties(template, props);

397

398

// HTML escaping

399

String userInput = "<script>alert('xss')</script>";

400

String safe = HtmlUtils.escapeHtml(userInput);

401

```

402

403

## Functional and Collection Utilities

404

405

### TriFunction

406

407

Functional interface for three-parameter functions.

408

409

```java { .api }

410

@FunctionalInterface

411

public interface TriFunction<T, U, V, R> {

412

R apply(T t, U u, V v);

413

414

default <W> TriFunction<T, U, V, W> andThen(Function<? super R, ? extends W> after);

415

}

416

```

417

418

### CollectionUtil

419

420

Collection manipulation utilities.

421

422

```java { .api }

423

public class CollectionUtil {

424

public static <T> List<T> collectionToList(Collection<T> collection);

425

public static <T> Set<T> collectionToSet(Collection<T> collection);

426

public static boolean isEmpty(Collection<?> collection);

427

public static boolean isNotEmpty(Collection<?> collection);

428

}

429

```

430

431

### Usage Examples

432

433

```java

434

// TriFunction usage

435

TriFunction<String, Integer, Boolean, String> formatter =

436

(name, age, active) -> String.format("%s (%d) - %s", name, age, active ? "Active" : "Inactive");

437

438

String result = formatter.apply("John", 30, true);

439

440

// Collection utilities

441

List<String> items = Arrays.asList("a", "b", "c");

442

Set<String> uniqueItems = CollectionUtil.collectionToSet(items);

443

boolean hasItems = CollectionUtil.isNotEmpty(items);

444

```

445

446

## Advanced Utilities

447

448

### PathMatcher

449

450

Path pattern matching utilities for URL routing.

451

452

```java { .api }

453

public class PathMatcher {

454

public static boolean matches(String pattern, String path);

455

public static Map<String, String> extractPathVariables(String pattern, String path);

456

}

457

```

458

459

### Retry

460

461

Retry mechanism utilities for robust operations.

462

463

```java { .api }

464

public class Retry {

465

public static <T> T execute(Supplier<T> operation, int maxAttempts);

466

public static <T> T execute(Supplier<T> operation, int maxAttempts, long delay);

467

public static void execute(Runnable operation, int maxAttempts);

468

}

469

```

470

471

### SecretGenerator

472

473

Secure random value generation utilities.

474

475

```java { .api }

476

public class SecretGenerator {

477

public static String generateSecret(int length);

478

public static byte[] generateRandomBytes(int length);

479

public static String generateUuid();

480

}

481

```

482

483

### Usage Examples

484

485

```java

486

// Path matching

487

boolean matches = PathMatcher.matches("/users/{id}", "/users/123");

488

Map<String, String> vars = PathMatcher.extractPathVariables("/users/{id}", "/users/123");

489

String userId = vars.get("id"); // "123"

490

491

// Retry operations

492

String result = Retry.execute(() -> {

493

return callExternalService();

494

}, 3, 1000); // 3 attempts, 1 second delay

495

496

// Generate secrets

497

String secret = SecretGenerator.generateSecret(32);

498

String uuid = SecretGenerator.generateUuid();

499

```

500

501

## HTTP and Web Utilities

502

503

### HttpPostRedirect

504

505

HTTP POST redirect utilities.

506

507

```java { .api }

508

public class HttpPostRedirect {

509

public static void sendPostRedirect(HttpServletResponse response, String url, Map<String, String> params);

510

public static String generateAutoSubmitForm(String url, Map<String, String> params);

511

}

512

```

513

514

### MimeTypeUtil

515

516

MIME type detection and handling utilities.

517

518

```java { .api }

519

public class MimeTypeUtil {

520

public static String getContentType(String filename);

521

public static boolean isTextType(String contentType);

522

public static boolean isImageType(String contentType);

523

}

524

```

525

526

### Usage Examples

527

528

```java

529

// POST redirect

530

Map<String, String> params = new HashMap<>();

531

params.put("token", "abc123");

532

params.put("state", "xyz789");

533

HttpPostRedirect.sendPostRedirect(response, "https://client.example.com/callback", params);

534

535

// MIME type detection

536

String contentType = MimeTypeUtil.getContentType("document.pdf");

537

boolean isText = MimeTypeUtil.isTextType("text/plain");

538

```

539

540

## Specialized Utilities

541

542

### KerberosSerializationUtils

543

544

Kerberos-specific serialization utilities.

545

546

```java { .api }

547

public class KerberosSerializationUtils {

548

public static byte[] serialize(Object obj) throws IOException;

549

public static <T> T deserialize(byte[] bytes, Class<T> clazz) throws IOException, ClassNotFoundException;

550

}

551

```

552

553

### MultiSiteUtils

554

555

Multi-site deployment utilities.

556

557

```java { .api }

558

public class MultiSiteUtils {

559

public static String getCurrentSite();

560

public static boolean isMultiSiteEnabled();

561

public static String getSiteFromRequest(HttpServletRequest request);

562

}

563

```

564

565

### ObjectUtil

566

567

General object manipulation utilities.

568

569

```java { .api }

570

public class ObjectUtil {

571

public static boolean isEqual(Object a, Object b);

572

public static int hashCode(Object... objects);

573

public static <T> T defaultIfNull(T object, T defaultValue);

574

}

575

```

576

577

This comprehensive utility package provides essential functionality for building robust Keycloak applications and integrations, covering everything from basic data manipulation to advanced cryptographic operations and web service utilities.