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
—
Essential utility classes providing fundamental operations for collections, date/time handling, JSON processing, system operations, and functional programming with enhanced exception handling.
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.DateTimeUtils;
import org.apereo.cas.util.JsonUtils;
import org.apereo.cas.util.AopUtils;
import org.springframework.util.MultiValueMap;
import java.time.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.*;Comprehensive collection manipulation utilities for maps, lists, and sets.
@UtilityClass
public class CollectionUtils {
// Map creation utilities - basic overloads
public static <K, V> Map<K, V> wrap(String key, Object value);
public static <K, V> Map<K, V> wrap(String key, Object value, String key2, Object value2);
public static <K, V> Map<K, V> wrap(String key, Object value, String key2, Object value2, String key3, Object value3);
public static <K, V> Map<K, V> wrap(String key, Object value, String key2, Object value2, String key3, Object value3, String key4, Object value4);
public static <K, V> Map<K, V> wrap(String key, Object value, String key2, Object value2, String key3, Object value3, String key4, Object value4, String key5, Object value5);
public static <K, V> Map<K, V> wrap(String key, Object value, String key2, Object value2, String key3, Object value3, String key4, Object value4, String key5, Object value5, String key6, Object value6);
// Map/Collection wrapping utilities
public static <K, V> Map<K, V> wrap(Multimap<K, V> source);
public static <K, V> Map<K, V> wrap(Map<K, V> source);
public static <T> List<T> wrap(T source);
public static <T> List<T> wrap(List<T> source);
public static <T> Set<T> wrap(Set<T> source);
// Collection creation utilities
public static <T> Set<T> wrapSet(T source);
public static <T> Set<T> wrapSet(T... source);
public static <T> Set<T> wrapHashSet(T... source);
public static <T> Set<T> wrapHashSet(Collection<T> source);
public static <T> List<T> wrapList(T... source);
public static <T> List<T> wrapArrayList(T... source);
public static <T> Map<String, T> wrapLinkedHashMap(String key, T source);
public static <T> Collection<T> wrapCollection(T... source);
// Collection conversion utilities
public static Map<String, Object> toSingleValuedMap(
Map<String, Object> attributes,
List<String> singleValuedAttributes
);
public static Map<String, List<Object>> toMultiValuedMap(
Map<String, Object> attributes
);
public static Map<String, List<Object>> fromCommaDelimitedValues(
Map<String, String> attributes
);
// Element extraction
public static Optional<Object> firstElement(Object obj);
public static <T> Optional<T> firstElement(Object obj, Class<T> clazz);
// Collection type conversion
public static <T extends Collection> T toCollection(Object obj, Class<T> clazz);
public static Set<Object> toCollection(Object obj);
// MultiValueMap operations
public static MultiValueMap<String, Object> asMultiValueMap(Map<String, ?> source);
public static MultiValueMap<String, Object> asMultiValueMap(
Map<String, ?> source,
String keyPattern
);
// Utility operations
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor);
public static Map<String, String> convertDirectedListToMap(Collection<String> inputList);
public static Map<String, Object> merge(Map<String, ?>... attributes);
}Creating and manipulating maps:
// Create maps from key-value pairs
Map<String, Object> user = CollectionUtils.wrap(
"name", "John Doe",
"email", "john@example.com"
);
// For more complex data, use multiple wrap calls and merge
Map<String, Object> roles = CollectionUtils.wrap("roles", Arrays.asList("USER", "ADMIN"));
Map<String, Object> fullUser = CollectionUtils.merge(user, roles);
// Convert to single-valued attributes
List<String> singleValued = Arrays.asList("name", "email");
Map<String, Object> singleValuedMap = CollectionUtils.toSingleValuedMap(user, singleValued);
// Convert to multi-valued map
Map<String, List<Object>> multiValuedMap = CollectionUtils.toMultiValuedMap(user);Working with collections:
// Extract first elements safely
List<String> names = Arrays.asList("John", "Jane", "Bob");
Optional<String> firstName = CollectionUtils.firstElement(names, String.class);
// Filter by distinct keys
List<User> users = getUsers();
List<User> uniqueByEmail = users.stream()
.filter(CollectionUtils.distinctByKey(User::getEmail))
.collect(Collectors.toList());
// Merge multiple maps
Map<String, Object> defaults = CollectionUtils.wrap("timeout", 30);
Map<String, Object> overrides = CollectionUtils.wrap("timeout", 60, "retries", 3);
Map<String, Object> merged = CollectionUtils.merge(defaults, overrides);Date and time utility methods for parsing, converting, and working with various temporal types.
@UtilityClass
public class DateTimeUtils {
// LocalDateTime operations
public static LocalDateTime localDateTimeOf(String value);
public static LocalDateTime localDateTimeOf(long time);
public static LocalDateTime localDateTimeOf(Date time);
// LocalDate operations
public static LocalDate localDateOf(long time);
// ZonedDateTime operations
public static ZonedDateTime zonedDateTimeOf(String value);
public static ZonedDateTime zonedDateTimeOf(TemporalAccessor time);
public static ZonedDateTime zonedDateTimeOf(Instant time);
public static ZonedDateTime zonedDateTimeOf(long time);
public static ZonedDateTime zonedDateTimeOf(long time, ZoneId zoneId);
public static ZonedDateTime zonedDateTimeOf(Date time);
public static ZonedDateTime zonedDateTimeOf(Calendar time);
// Date conversion
public static Date dateOf(ChronoZonedDateTime time);
public static Date dateOf(LocalDate time);
public static Date dateOf(LocalDateTime time);
public static Date dateOf(Instant time);
// Parsing utilities
public static ZonedDateTime convertToZonedDateTime(String value);
// Time unit conversion
public static TimeUnit toTimeUnit(ChronoUnit chronoUnit);
public static ChronoUnit toChronoUnit(TimeUnit timeUnit);
}Date/time creation and conversion:
// Create from various sources
LocalDateTime now = DateTimeUtils.localDateTimeOf(System.currentTimeMillis());
LocalDateTime parsed = DateTimeUtils.localDateTimeOf("2024-01-15T10:30:00");
ZonedDateTime zoned = DateTimeUtils.zonedDateTimeOf(System.currentTimeMillis(), ZoneId.of("America/New_York"));
// Convert to legacy Date objects
Date legacyDate = DateTimeUtils.dateOf(now);
Date zonedDate = DateTimeUtils.dateOf(zoned);
// Parse ISO strings with timezone
ZonedDateTime fromIso = DateTimeUtils.convertToZonedDateTime("2024-01-15T10:30:00-05:00");Time unit operations:
// Convert between time units
TimeUnit minutes = DateTimeUtils.toTimeUnit(ChronoUnit.MINUTES);
ChronoUnit hours = DateTimeUtils.toChronoUnit(TimeUnit.HOURS);
// Use in cache configurations
Duration timeout = Duration.of(30, DateTimeUtils.toChronoUnit(TimeUnit.SECONDS));JSON utility methods for rendering objects and validating JSON strings.
@UtilityClass
public class JsonUtils {
// Object rendering
public String render(Object model);
public String render(ObjectMapper mapper, Object model);
// HTTP response rendering
public void render(Object model, HttpServletResponse response);
public void render(HttpServletResponse response);
public void renderException(Exception ex, HttpServletResponse response);
// Validation
public boolean isValidJson(String json);
}JSON serialization:
// Render objects to JSON
User user = new User("John", "john@example.com");
String json = JsonUtils.render(user);
// Custom ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String prettyJson = JsonUtils.render(mapper, user);
// Render to HTTP response
@RequestMapping("/api/user")
public void getUser(HttpServletResponse response) {
User user = userService.getCurrentUser();
JsonUtils.render(user, response);
}JSON validation:
// Validate JSON strings
String userInput = request.getParameter("json");
if (JsonUtils.isValidJson(userInput)) {
// Process valid JSON
processUserData(userInput);
} else {
// Handle invalid JSON
throw new IllegalArgumentException("Invalid JSON format");
}Utility class for Aspect-Oriented Programming operations.
@UtilityClass
public class AopUtils {
// JoinPoint utilities
public static JoinPoint unWrapJoinPoint(JoinPoint point);
}AOP join point handling:
@Aspect
@Component
public class SecurityAspect {
@Around("@annotation(Secured)")
public Object checkSecurity(ProceedingJoinPoint joinPoint) throws Throwable {
// Unwrap nested join points
JoinPoint unwrapped = AopUtils.unWrapJoinPoint(joinPoint);
// Perform security checks
checkPermissions(unwrapped.getSignature().getName());
return joinPoint.proceed();
}
}The library includes several other utility classes for specialized operations:
Compression and decompression utilities for data processing.
Hashing and digest utilities for data integrity verification.
Text encoding and decoding utilities supporting various character sets.
Network address utilities for IP address validation and manipulation.
Logging configuration and message formatting utilities.
Regular expression utilities with pre-compiled patterns for common operations.
Spring resource handling utilities for classpath and file system resources.
Network socket utilities for port availability checking and socket configuration.
System information and environment utilities for runtime introspection.
// Get system properties and environment info
Map<String, String> systemInfo = SystemUtils.getSystemProperties();
String javaVersion = SystemUtils.getJavaVersion();
boolean isUnix = SystemUtils.isUnix();
// Resource handling
Resource configResource = ResourceUtils.getResourceFrom("classpath:config.properties");
InputStream stream = ResourceUtils.getResourceStream(configResource);Install with Tessl CLI
npx tessl i tessl/maven-org-apereo-cas--cas-server-core-util-api