com.vaadin.data.converter.StringToUuidConverter Maven / Gradle / Ivy
/*
* Copyright (C) 2000-2024 Vaadin Ltd
*
* This program is available under Vaadin Commercial License and Service Terms.
*
* See for the full
* license.
*/
package com.vaadin.data.converter;
import java.util.UUID;
import com.vaadin.data.Converter;
import com.vaadin.data.ErrorMessageProvider;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
/**
* A converter that converts from {@link String} to {@link UUID} and back.
*
* Leading and trailing white spaces are ignored when converting from a String.
*
*
* The String representation uses the canonical format of 32-characters with a
* hyphen to separate each of five groups of hexadecimal digits as defined in:
* RFC 4122: A Universally Unique IDentifier (UUID) URN Namespace
* http://www.ietf.org/rfc/rfc4122.txt
*
*
* @author Vaadin Ltd
* @since 8.8
*/
public class StringToUuidConverter implements Converter {
private ErrorMessageProvider errorMessageProvider;
/**
* Constructs a converter for String to UUID and back.
*
* @param errorMessage
* the error message to use if conversion fails
*/
public StringToUuidConverter(String errorMessage) {
this(ctx -> errorMessage);
}
/**
* Constructs a new converter instance with the given error message
* provider. Empty strings are converted to null
.
*
* @param errorMessageProvider
* the error message provider to use if conversion fails
*/
public StringToUuidConverter(ErrorMessageProvider errorMessageProvider) {
this.errorMessageProvider = errorMessageProvider;
}
@Override
public Result convertToModel(String value, ValueContext context) {
if (value == null) {
return Result.ok(null);
}
// Remove leading and trailing white space
value = value.trim();
// Parse string as UUID.
UUID uuid = null;
try {
uuid = UUID.fromString(value);
} catch (java.lang.IllegalArgumentException e) {
// Faulty input. Let `uuid` default to null. Report error below.
}
if (null != uuid) {
return Result.ok(uuid); // Return the UUID object, converted from
// String.
} else {
return Result.error(this.errorMessageProvider.apply(context));
}
}
@Override
public String convertToPresentation(UUID value, ValueContext context) {
if (value == null) {
return null;
}
// `java.util.UUID::toString` generates a textual representation of a
// UUID’s 128-bits as a lowercase hexadecimal `String` in canonical
// 32-character format with four hyphens separating groups of digits.
// https://docs.oracle.com/javase/10/docs/api/java/util/UUID.html#toString()
return value.toString();
}
}