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.0A 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.
Maven Coordinates:
<dependency>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-core-util-api</artifactId>
<version>7.2.4</version>
</dependency>Java Compatibility: Java 11+
Framework Integration: Spring Framework 6.x, Spring Boot 3.x
// Core utility classes
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.DateTimeUtils;
import org.apereo.cas.util.JsonUtils;
import org.apereo.cas.util.function.FunctionUtils;
// Cryptographic utilities
import org.apereo.cas.util.crypto.CipherExecutor;
import org.apereo.cas.util.cipher.AbstractCipherExecutor;
import org.apereo.cas.util.serialization.SerializationUtils;
// HTTP clients
import org.apereo.cas.util.http.HttpClient;
import org.apereo.cas.util.http.SimpleHttpClient;
// Generators
import org.apereo.cas.util.gen.RandomStringGenerator;
import org.apereo.cas.util.gen.DefaultRandomStringGenerator;
// Spring integration
import org.apereo.cas.util.spring.ApplicationContextProvider;
// JWT utilities
import org.apereo.cas.util.jwt.JsonWebTokenSigner;
import org.apereo.cas.util.jwt.JsonWebTokenEncryptor;import org.apereo.cas.util.CollectionUtils;
import java.util.*;
// Create maps easily
Map<String, Object> attributes = CollectionUtils.wrap("key1", "value1", "key2", "value2");
// Convert to multi-valued map
Map<String, List<Object>> multiValued = CollectionUtils.toMultiValuedMap(attributes);
// Filter by distinct keys
List<User> uniqueUsers = users.stream()
.filter(CollectionUtils.distinctByKey(User::getEmail))
.collect(Collectors.toList());import org.apereo.cas.util.DateTimeUtils;
import java.time.*;
// Parse various date formats
LocalDateTime dateTime = DateTimeUtils.localDateTimeOf("2024-01-15T10:30:00");
ZonedDateTime zonedTime = DateTimeUtils.zonedDateTimeOf(System.currentTimeMillis());
// Convert time units
TimeUnit timeUnit = DateTimeUtils.toTimeUnit(ChronoUnit.HOURS);import org.apereo.cas.util.function.FunctionUtils;
// Conditional operations
String result = FunctionUtils.doIfNotBlank(inputString, String::toUpperCase);
// Exception handling
String safeResult = FunctionUtils.doAndHandle(() -> riskyOperation(),
Exception.class,
ex -> "default");
// Retry operations
String retryResult = FunctionUtils.doAndRetry(() -> unreliableOperation(),
3,
1000);The CAS Core Utilities library is organized into specialized packages, each providing focused functionality:
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.
// Collection utilities
Map<String, Object> map = CollectionUtils.wrap("user", "john", "role", "admin");
Optional<String> first = CollectionUtils.firstElement(collection, String.class);
// Date/time utilities
ZonedDateTime now = DateTimeUtils.zonedDateTimeOf(System.currentTimeMillis());
LocalDate date = DateTimeUtils.localDateOf(timestamp);
// Functional programming with exception handling
String result = FunctionUtils.doAndHandle(() -> parseJson(input),
JsonException.class,
ex -> "{}");Comprehensive cryptographic capabilities including cipher executors, password encoders, certificate utilities, and key management. Supports various encryption algorithms and provides secure defaults.
// Abstract cipher executor
public class MyCipher extends AbstractCipherExecutor<String, String> {
@Override
public String encode(String value, Object[] parameters) {
return encrypt(value);
}
@Override
public String decode(String value, Object[] parameters) {
return decrypt(value);
}
}
// Certificate operations
X509Certificate cert = CertUtils.readCertificate(certResource);
PublicKey publicKey = AbstractCipherExecutor.extractPublicKeyFromResource(keyPath);Robust HTTP client implementations with factory patterns, request/response utilities, and integration with Apache HttpClient. Supports various authentication methods and connection pooling.
// HTTP client usage
HttpClient client = new SimpleHttpClient();
HttpMessage message = new HttpMessage(new URL("https://api.example.com"), "POST");
message.setContentType("application/json");
message.setEntity("{\"key\":\"value\"}");
boolean success = client.sendMessageToEndPoint(message);
HttpMessage response = client.sendMessageToEndPoint(new URL("https://api.example.com"));Random string and numeric generators for creating secure tokens, identifiers, and cryptographic material. Multiple output formats including Base64, hex, and custom alphabets.
// Random string generation
RandomStringGenerator generator = new DefaultRandomStringGenerator();
String token = generator.getNewString(32);
// Numeric generation
NumericGenerator numGen = new DefaultRandomNumberGenerator();
long id = numGen.getNextLong();
// Specialized generators
RandomStringGenerator base64Gen = new Base64RandomStringGenerator();
RandomStringGenerator hexGen = new HexRandomStringGenerator();Deep Spring Framework integration with application context management, conditional beans, configuration properties, and Spring Boot support. Includes custom conditions and bean lifecycle management.
// Application context access
ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
Optional<MyBean> bean = ApplicationContextProvider.getBean("myBean", MyBean.class);
// Bean registration
ApplicationContextProvider.registerBeanIntoApplicationContext(ctx, myBean, "beanName");
// Configuration properties
Optional<CasConfigurationProperties> config =
ApplicationContextProvider.getCasConfigurationProperties();JSON Web Token signing and encryption utilities with support for various algorithms and key management strategies.
// JWT signing
JsonWebTokenSigner signer = new JsonWebTokenSigner(secretKey, algorithm);
JwtClaims claims = new JwtClaims();
claims.setSubject("user123");
String jwt = signer.sign(claims);
// JWT encryption
JsonWebTokenEncryptor encryptor = new JsonWebTokenEncryptor(encryptionKey, keyAlgorithm);
String encryptedJwt = encryptor.encrypt(payload);Object serialization utilities with support for various formats, compression, and encryption. Includes Jackson integration and custom serialization plans.
// Basic serialization
byte[] bytes = SerializationUtils.serialize(myObject);
MyObject restored = SerializationUtils.deserialize(bytes, MyObject.class);
// Encrypted serialization
byte[] encrypted = SerializationUtils.serializeAndEncodeObject(cipher, myObject);
MyObject decrypted = SerializationUtils.decodeAndDeserializeObject(cipher, encrypted,
MyObject.class);Message sanitization and text processing utilities for secure handling of user input and system messages.
// Message sanitization
MessageSanitizer sanitizer = new DefaultMessageSanitizer();
String clean = sanitizer.sanitize(userInput);
// Principal name transformation
PrincipalNameTransformer transformer = new ConvertCasePrincipalNameTransformer();
String transformed = transformer.transform("UserName"); // returns "username"Advanced functional programming utilities with enhanced exception handling, conditional operations, and retry mechanisms.
// Conditional functions
Function<String, String> processor = FunctionUtils.doIf(
StringUtils::isNotBlank,
String::toUpperCase,
s -> "DEFAULT"
);
// Exception handling with retry
String result = FunctionUtils.doAndRetry(() -> {
return callExternalService();
}, 3, 1000, IOException.class);
// Null-safe operations
FunctionUtils.doIfNotNull(user, u -> updateLastLogin(u));Additional specialized utilities including cache management, file watching, SSL utilities, JPA converters, concurrency utilities, and virtual threading support.
// File watching
WatcherService watcher = new FileWatcherService();
watcher.start("config", path -> reloadConfiguration());
// Cache management
DistributedCacheManager<String, Object> cache = new MyDistributedCacheManager();
cache.set("key", value, Duration.ofMinutes(30));
// Virtual threading (Java 21+)
VirtualThreadDelegate delegate = new VirtualThreadDelegate();
ThreadFactory factory = delegate.virtualThreadFactory("cas-");
Thread vThread = delegate.newVirtualThread("worker", task);