Chapter 42. Configuring Media Types

Red Hat JBoss Data Grid lets you configure the media type for data in the cache. In other words, you can set a media type that defines the storage format for data in the cache.

JBoss Data Grid allows clients to write and read data in different storage formats and automatically converts between formats when necessary.

42.1. Default Media Type

The default media type is application/octet-stream for both keys and values with the following exceptions:

  • Indexed caches have a default media type of application/x-protostream.
  • Caches that use compatibility mode have a default media type of application/x-java-object.

42.2. Supported Media Types

Red Hat JBoss Data Grid lets clients read and write data in different formats and automatically converts between formats.

JBoss Data Grid supports several data formats that are interchangeable with one another, as follows:

  • application/x-java-object
  • application/octet-stream
  • application/x-www-form-urlencoded
  • text/plain

JBoss Data Grid also supports data formats that it must convert to and from the data formats in the preceding list, as follows:

  • application/xml
  • application/json
  • application/x-jboss-marshalling
  • application/x-java-serialized
  • application/x-protostream

In addition, JBoss Data Grid supports conversion between application/x-protostream and application/json.

42.3. Declaratively Configuring Media Types

The following is an example configuration that defines the media type for keys and values:

<cache>
   <encoding>
      <key media-type="application/x-java-object; type=java.lang.Integer"/>
      <value media-type="application/xml; charset=UTF-8"/>
   </encoding>
</cache>

42.4. Programmatically Configuring Media Types

Use the ConfigurationBuilder interface to programmatically configure the media type, as in the following example:

ConfigurationBuilder cfg = new ConfigurationBuilder();

cfg.encoding().key().mediaType("text/plain");
cfg.encoding().value().mediaType("application/json");

42.5. Overriding Media Types

You can programmatically override the media type that is configured for the cache, as in the following example:

DefaultCacheManager cacheManager = new DefaultCacheManager();

// The cache will store POJO for keys and values
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.encoding().key().mediaType("application/x-java-object");
cfg.encoding().key().mediaType("application/x-java-object");

cacheManager.defineConfiguration("mycache", cfg.build());

Cache<Integer, Person> cache = cacheManager.getCache("mycache");

cache.put(1, new Person("John","Doe"));

// Wraps cache using 'application/x-java-object' for keys but JSON for values.
cache.getAdvancedCache().withMediaType("application/x-java-object", "application/json");

byte[] json = cache.get(1);

This configuration returns the value in JSON format, as follows:

{
   "_type":"org.infinispan.sample.Person",
   "name":"John",
   "surname":"Doe"
}