Clone wiki

specter / converters


The framework provides several implementations of converters to types:

  • java.lang.BigDecimal
  • java.lang.BigInteger
  • byte and java.lang.Byte
  • double and java.lang.Double
  • float and java.lang.Float
  • int and java.lang.Integer
  • long and java.lang.Long
  • short and java.lang.Short
  • java.lang.String
  • java.sql.Date
  • java.sql.Time
  • java.sql.Timestamp

But sometimes we need to define a whole new implementation or a different behaviour of them. This is actually possible by defining different components that will allow us to acquire the definition of our own rule. First of all, we need an custom annotation that we will use to register the new convertion rule within the application. This annotation could be something like this:

public @interface ApplyLocaleConverter {

As you can see, it has nothing different as any other annotation you might have seen. The next step would be to define the actual convertion rule. For that, we have to keep in mind that this rule has to implement the interface edu.uoc.pfc.specter.core.converter.DataConverter, which will ask you to specify the type you're converting the incoming information to. Having said that, we can start defining our rule as follows:

@ConvertionRule(associatedTo=ApplyLocaleConverter.class,target = Locale.class)
public class LocaleConvertionRule implements DataConverter<Locale>{

	public Locale convert(Annotation p_SourceAnnotation, Object p_oSource, Class<Locale> p_oType) {

		String[] aLocale = ((String)p_oSource).split("_");
		if(aLocale.length == 1)
			return new Locale(aLocale[0]);
		else if(aLocale.length == 2)
			return new Locale(aLocale[0],aLocale[1]);
		else if(aLocale.length == 3)
			return new Locale(aLocale[0], aLocale[1], aLocale[2]);
		return null;

The first thing that i've got to highlight is the use of the annotation @ConvertionRule. This annotation is the one that makes things happened. I mean, we need this annotation to let the framework know about our new rule by specifing to different parameter: the annotation we're going to use to reference our new rule within our code, and the the type we're converting to. From now on, whenever we use the annotation @ApplyLocaleConverter within our code, the framework will register our convertion rule in order to execute it when an attribute type matched our target type.

Note: Because of implementation limitations, the conversions rule only can be used at class level, which means that the same rule will be applied to all attributes with the same type.