Apereo CAS Core Utilities - A comprehensive utility library providing functional programming constructs, encryption utilities, configuration helpers, and core infrastructure components for the Central Authentication Service framework
npx @tessl/cli install tessl/maven-org-apereo-cas--cas-server-core-util-api@7.2.00
# Apereo CAS Core Utilities
1
2
A comprehensive utility library providing essential infrastructure components for the Central Authentication Service (CAS) framework. This library offers functional programming constructs, cryptographic utilities, HTTP clients, configuration helpers, and Spring Framework integration.
3
4
## Package Information
5
6
**Maven Coordinates:**
7
```xml
8
<dependency>
9
<groupId>org.apereo.cas</groupId>
10
<artifactId>cas-server-core-util-api</artifactId>
11
<version>7.2.4</version>
12
</dependency>
13
```
14
15
**Java Compatibility:** Java 11+
16
**Framework Integration:** Spring Framework 6.x, Spring Boot 3.x
17
18
## Core Imports
19
20
```java
21
// Core utility classes
22
import org.apereo.cas.util.CollectionUtils;
23
import org.apereo.cas.util.DateTimeUtils;
24
import org.apereo.cas.util.JsonUtils;
25
import org.apereo.cas.util.function.FunctionUtils;
26
27
// Cryptographic utilities
28
import org.apereo.cas.util.crypto.CipherExecutor;
29
import org.apereo.cas.util.cipher.AbstractCipherExecutor;
30
import org.apereo.cas.util.serialization.SerializationUtils;
31
32
// HTTP clients
33
import org.apereo.cas.util.http.HttpClient;
34
import org.apereo.cas.util.http.SimpleHttpClient;
35
36
// Generators
37
import org.apereo.cas.util.gen.RandomStringGenerator;
38
import org.apereo.cas.util.gen.DefaultRandomStringGenerator;
39
40
// Spring integration
41
import org.apereo.cas.util.spring.ApplicationContextProvider;
42
43
// JWT utilities
44
import org.apereo.cas.util.jwt.JsonWebTokenSigner;
45
import org.apereo.cas.util.jwt.JsonWebTokenEncryptor;
46
```
47
48
## Basic Usage Examples
49
50
### Working with Collections
51
```java
52
import org.apereo.cas.util.CollectionUtils;
53
import java.util.*;
54
55
// Create maps easily
56
Map<String, Object> attributes = CollectionUtils.wrap("key1", "value1", "key2", "value2");
57
58
// Convert to multi-valued map
59
Map<String, List<Object>> multiValued = CollectionUtils.toMultiValuedMap(attributes);
60
61
// Filter by distinct keys
62
List<User> uniqueUsers = users.stream()
63
.filter(CollectionUtils.distinctByKey(User::getEmail))
64
.collect(Collectors.toList());
65
```
66
67
### Date/Time Operations
68
```java
69
import org.apereo.cas.util.DateTimeUtils;
70
import java.time.*;
71
72
// Parse various date formats
73
LocalDateTime dateTime = DateTimeUtils.localDateTimeOf("2024-01-15T10:30:00");
74
ZonedDateTime zonedTime = DateTimeUtils.zonedDateTimeOf(System.currentTimeMillis());
75
76
// Convert time units
77
TimeUnit timeUnit = DateTimeUtils.toTimeUnit(ChronoUnit.HOURS);
78
```
79
80
### Functional Programming with Exception Handling
81
```java
82
import org.apereo.cas.util.function.FunctionUtils;
83
84
// Conditional operations
85
String result = FunctionUtils.doIfNotBlank(inputString, String::toUpperCase);
86
87
// Exception handling
88
String safeResult = FunctionUtils.doAndHandle(() -> riskyOperation(),
89
Exception.class,
90
ex -> "default");
91
92
// Retry operations
93
String retryResult = FunctionUtils.doAndRetry(() -> unreliableOperation(),
94
3,
95
1000);
96
```
97
98
## Architecture
99
100
The CAS Core Utilities library is organized into specialized packages, each providing focused functionality:
101
102
### Core Infrastructure
103
- **org.apereo.cas.util** - Essential utility classes for collections, dates, JSON, logging, and system operations
104
- **org.apereo.cas.util.function** - Functional programming utilities with enhanced exception handling and conditional operations
105
106
### Security & Cryptography
107
- **org.apereo.cas.util.cipher** - Comprehensive cipher executors for encryption, signing, and key management
108
- **org.apereo.cas.util.crypto** - Certificate utilities, password encoders, and cryptographic helper functions
109
- **org.apereo.cas.util.jwt** - JSON Web Token signing and encryption capabilities
110
111
### Data Management
112
- **org.apereo.cas.util.serialization** - Object serialization utilities with Jackson integration
113
- **org.apereo.cas.util.gen** - Random string and numeric generators for tokens and identifiers
114
115
### Network & Communication
116
- **org.apereo.cas.util.http** - HTTP client implementations and request/response utilities
117
118
### Framework Integration
119
- **org.apereo.cas.util.spring** - Deep Spring Framework integration including application context management, conditional beans, and configuration
120
- **org.apereo.cas.util.text** - Message sanitization and text processing utilities
121
122
### Specialized Components
123
- **org.apereo.cas.util.transforms** - Principal name transformation utilities
124
- **org.apereo.cas.util.cache** - Distributed cache management
125
- **org.apereo.cas.util.io** - File system watching and I/O operations
126
127
## Capabilities
128
129
### [Core Utilities](core-utilities.md)
130
Essential utility classes for everyday operations including collection manipulation, date/time handling, JSON processing, and system utilities. Features powerful functional programming constructs with exception handling.
131
132
```java
133
// Collection utilities
134
Map<String, Object> map = CollectionUtils.wrap("user", "john", "role", "admin");
135
Optional<String> first = CollectionUtils.firstElement(collection, String.class);
136
137
// Date/time utilities
138
ZonedDateTime now = DateTimeUtils.zonedDateTimeOf(System.currentTimeMillis());
139
LocalDate date = DateTimeUtils.localDateOf(timestamp);
140
141
// Functional programming with exception handling
142
String result = FunctionUtils.doAndHandle(() -> parseJson(input),
143
JsonException.class,
144
ex -> "{}");
145
```
146
147
### [Cryptography](cryptography.md)
148
Comprehensive cryptographic capabilities including cipher executors, password encoders, certificate utilities, and key management. Supports various encryption algorithms and provides secure defaults.
149
150
```java
151
// Abstract cipher executor
152
public class MyCipher extends AbstractCipherExecutor<String, String> {
153
@Override
154
public String encode(String value, Object[] parameters) {
155
return encrypt(value);
156
}
157
158
@Override
159
public String decode(String value, Object[] parameters) {
160
return decrypt(value);
161
}
162
}
163
164
// Certificate operations
165
X509Certificate cert = CertUtils.readCertificate(certResource);
166
PublicKey publicKey = AbstractCipherExecutor.extractPublicKeyFromResource(keyPath);
167
```
168
169
### [HTTP Clients](http-clients.md)
170
Robust HTTP client implementations with factory patterns, request/response utilities, and integration with Apache HttpClient. Supports various authentication methods and connection pooling.
171
172
```java
173
// HTTP client usage
174
HttpClient client = new SimpleHttpClient();
175
HttpMessage message = new HttpMessage(new URL("https://api.example.com"), "POST");
176
message.setContentType("application/json");
177
message.setEntity("{\"key\":\"value\"}");
178
179
boolean success = client.sendMessageToEndPoint(message);
180
HttpMessage response = client.sendMessageToEndPoint(new URL("https://api.example.com"));
181
```
182
183
### [Generators](generators.md)
184
Random string and numeric generators for creating secure tokens, identifiers, and cryptographic material. Multiple output formats including Base64, hex, and custom alphabets.
185
186
```java
187
// Random string generation
188
RandomStringGenerator generator = new DefaultRandomStringGenerator();
189
String token = generator.getNewString(32);
190
191
// Numeric generation
192
NumericGenerator numGen = new DefaultRandomNumberGenerator();
193
long id = numGen.getNextLong();
194
195
// Specialized generators
196
RandomStringGenerator base64Gen = new Base64RandomStringGenerator();
197
RandomStringGenerator hexGen = new HexRandomStringGenerator();
198
```
199
200
### [Spring Integration](spring-integration.md)
201
Deep Spring Framework integration with application context management, conditional beans, configuration properties, and Spring Boot support. Includes custom conditions and bean lifecycle management.
202
203
```java
204
// Application context access
205
ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
206
Optional<MyBean> bean = ApplicationContextProvider.getBean("myBean", MyBean.class);
207
208
// Bean registration
209
ApplicationContextProvider.registerBeanIntoApplicationContext(ctx, myBean, "beanName");
210
211
// Configuration properties
212
Optional<CasConfigurationProperties> config =
213
ApplicationContextProvider.getCasConfigurationProperties();
214
```
215
216
### [JWT Utilities](jwt-utilities.md)
217
JSON Web Token signing and encryption utilities with support for various algorithms and key management strategies.
218
219
```java
220
// JWT signing
221
JsonWebTokenSigner signer = new JsonWebTokenSigner(secretKey, algorithm);
222
JwtClaims claims = new JwtClaims();
223
claims.setSubject("user123");
224
String jwt = signer.sign(claims);
225
226
// JWT encryption
227
JsonWebTokenEncryptor encryptor = new JsonWebTokenEncryptor(encryptionKey, keyAlgorithm);
228
String encryptedJwt = encryptor.encrypt(payload);
229
```
230
231
### [Serialization](serialization.md)
232
Object serialization utilities with support for various formats, compression, and encryption. Includes Jackson integration and custom serialization plans.
233
234
```java
235
// Basic serialization
236
byte[] bytes = SerializationUtils.serialize(myObject);
237
MyObject restored = SerializationUtils.deserialize(bytes, MyObject.class);
238
239
// Encrypted serialization
240
byte[] encrypted = SerializationUtils.serializeAndEncodeObject(cipher, myObject);
241
MyObject decrypted = SerializationUtils.decodeAndDeserializeObject(cipher, encrypted,
242
MyObject.class);
243
```
244
245
### [Text Processing](text-processing.md)
246
Message sanitization and text processing utilities for secure handling of user input and system messages.
247
248
```java
249
// Message sanitization
250
MessageSanitizer sanitizer = new DefaultMessageSanitizer();
251
String clean = sanitizer.sanitize(userInput);
252
253
// Principal name transformation
254
PrincipalNameTransformer transformer = new ConvertCasePrincipalNameTransformer();
255
String transformed = transformer.transform("UserName"); // returns "username"
256
```
257
258
### [Functional Programming](functional-programming.md)
259
Advanced functional programming utilities with enhanced exception handling, conditional operations, and retry mechanisms.
260
261
```java { .api }
262
// Conditional functions
263
Function<String, String> processor = FunctionUtils.doIf(
264
StringUtils::isNotBlank,
265
String::toUpperCase,
266
s -> "DEFAULT"
267
);
268
269
// Exception handling with retry
270
String result = FunctionUtils.doAndRetry(() -> {
271
return callExternalService();
272
}, 3, 1000, IOException.class);
273
274
// Null-safe operations
275
FunctionUtils.doIfNotNull(user, u -> updateLastLogin(u));
276
```
277
278
### [Specialized Utilities](specialized-utilities.md)
279
Additional specialized utilities including cache management, file watching, SSL utilities, JPA converters, concurrency utilities, and virtual threading support.
280
281
```java
282
// File watching
283
WatcherService watcher = new FileWatcherService();
284
watcher.start("config", path -> reloadConfiguration());
285
286
// Cache management
287
DistributedCacheManager<String, Object> cache = new MyDistributedCacheManager();
288
cache.set("key", value, Duration.ofMinutes(30));
289
290
// Virtual threading (Java 21+)
291
VirtualThreadDelegate delegate = new VirtualThreadDelegate();
292
ThreadFactory factory = delegate.virtualThreadFactory("cas-");
293
Thread vThread = delegate.newVirtualThread("worker", task);
294
```