# ConversionService

ConversionService converts an object to the specified type. One common application is to convert to and from a string for typed value properties in the model. Another common application is to convert an input (such as a file) to a resource when instantiating the model.

A ConversionService implementation can delegate to other conversion services to create a conversion chain. In fact, a common conversion of an IFile to an XmlResource is a chain of two ConversionService implementations.

Sapphire includes a number of ConversionService implementations.

##servicess##

Example

In the purchase order sample, a custom ConversionService implementation is used because the default file extension for purchase order files is "po" rather than "xml" and PurchaseOrder element does not have XML binding annotations. The combination of these two factors prevent the framework-provided ConversionService implementations from engaging.

    @Service( impl = PurchaseOrderResourceConversionService.class )

    public interface PurchaseOrder extends Element
    {
        ...
    }

    public class PurchaseOrderResourceConversionService extends ConversionService<Object,RootXmlResource>
    {
        public PurchaseOrderResourceConversionService()
        {
            super( Object.class, RootXmlResource.class );
        }

        @Override
        public RootXmlResource convert( Object object )
        {
            final ByteArrayResourceStore store = service( MasterConversionService.class ).convert( object, ByteArrayResourceStore.class );

            if( store != null )
            {
                return new RootXmlResource( new XmlResourceStore( store ) );
            }

            return null;
        }
    }

Note the use of chaining as part of the presented ConversionService implementation. The input could be any number of things, but as long as another ConversionService implementation knows how to convert it to a ByteArrayResourceStore, this implementation will take the conversion the rest of the way to a Resource.

Copyright (c) 2016 Oracle
Content made available under the terms of Eclipse Public License.