É possível usar os plug-ins DataSerializer para ignorar o aumento de objetos automático e recuperar manualmente os atributos dos dados que já foram serializados. É possível também usar o DataSerializer para inserir e atualizar dados em seu formulário serializado. Esse uso pode ser útil quando apenas parte dos dados precisa ser acessada ou quando os dados precisam ser transmitidos entre os sistemas.
Esta tarefa usa o modo de cópia COPY_TO_BYTES_RAW com os plug-ins MapSerializerPlugin e ValueSerializerPlugin. O MapSerializer é o ponto de plug-in principal para a interface BackingMap. Dois plug-ins aninhados são incluídos, o KeyDataSerializer e o ValueDataSerializer. Como o produto não suporta plug-ins aninhados, o plug-in BaseMapSerializer suporta artificialmente estes plug-ins aninhados ou ligados. Portanto, quando usar essas APIs no contêiner OSGi, o MapSerializer será o único proxy. Todos os plug-ins aninhados não devem ser armazenados em cache dentro de outros plug-ins dependentes, como um carregador, a menos que ele também atenda aos eventos de ciclo de vida do BackingMap, de modo que suas referências de suporte possam ser atualizadas.
Quando COPY_TO_BYTES_RAW é configurado, todos os métodos ObjectMap retornam objetos SerializedValue, permitindo que o usuário recupere o formulário serializado ou o formulário do objeto Java do valor.
Ao usar um plug-in KeySerializerPlugin, todos os métodos que retornam chaves, como os plug-ins MapIndexPlugin ou Loader retornam objetos SerializedKey.
Quando os dados já estiverem no formulário serializado, os dados são inseridos com o uso dos mesmos objetos SerializedKey e SerializedValue. Quando os dados estiverem no formato byte[], os factories DataObjectKeyFactory e DataObjectValueFactory serão usados para criar a chave apropriada ou um wrapper de valor. Os factories estão disponíveis no DataObjectContext, que podem ser acessados a partir do SerializerAccessor para o BackingMap ou a partir da implementação do DataSerializer.
O exemplo neste tópico demonstra como concluir as ações a seguir:
import java.io.IOException;
import com.ibm.websphere.objectgrid.CopyMode;
import com.ibm.websphere.objectgrid.ObjectGrid;
import com.ibm.websphere.objectgrid.ObjectGridException;
import com.ibm.websphere.objectgrid.ObjectMap;
import com.ibm.websphere.objectgrid.Session;
import com.ibm.websphere.objectgrid.io.XsDataOutputStream;
import com.ibm.websphere.objectgrid.plugins.io.SerializerAccessor;
import com.ibm.websphere.objectgrid.plugins.io.ValueSerializerPlugin;
import com.ibm.websphere.objectgrid.plugins.io.dataobject.DataObjectContext;
import com.ibm.websphere.objectgrid.plugins.io.dataobject.SerializedKey;
import com.ibm.websphere.objectgrid.plugins.io.dataobject.SerializedValue;
/**
* Use the DataSerializer to serialize an Order key.
*/
public byte[] serializeOrderKey(ObjectGrid grid, String key)
throws IOException {
SerializerAccessor sa = grid.getMap("Order").getSerializerAccessor();
DataObjectContext dftObjCtx = sa.getDefaultContext();
XsDataOutputStream out = dftObjCtx.getDataStreamManager()
.createOutputStream();
sa.getMapSerializerPlugin().getKeySerializerPlugin()
.serializeDataObject(sa.getDefaultContext(), key, out);
return out.toByteArray();
}
/**
* Use the DataSerializer to serialize an Order value.
*/
public byte[] serializeOrderValue(ObjectGrid grid, Order value)
throws IOException {
SerializerAccessor sa = grid.getMap("Order").getSerializerAccessor();
DataObjectContext dftObjCtx = sa.getDefaultContext();
XsDataOutputStream out = dftObjCtx.getDataStreamManager()
.createOutputStream();
sa.getMapSerializerPlugin().getValueSerializerPlugin()
.serializeDataObject(sa.getDefaultContext(), value, out);
return out.toByteArray();
}
/**
* Retrieve a single Order in serialized form.
*/
public byte[] fetchOrderRAWBytes(Session session, String key)
throws ObjectGridException {
ObjectMap map = session.getMap("Order");
// Override the CopyMode to retrieve the serialized form of the value.
// This process affects all API methods from this point on for the life
// of the Session.
map.setCopyMode(CopyMode.COPY_TO_BYTES_RAW, null);
SerializedValue serValue = (SerializedValue) map.get(key);
if (serValue == null)
return null;
// Retrieve the byte array and return it to the caller.
return serValue.getInputStream().toByteArray();
}
/**
* Retrieve one or more attributes from the Order without inflating the
* Order object.
*/
public Object[] fetchOrderAttribute(Session session, String key,
String... attributes) throws ObjectGridException, IOException {
ObjectMap map = session.getMap("Order");
// Override the CopyMode to retrieve the serialized form of the value.
// This process affects all API methods from this point on for the life
// of the Session.
map.setCopyMode(CopyMode.COPY_TO_BYTES_RAW, null);
SerializedValue serValue = (SerializedValue) map.get(key);
if (serValue == null)
return null;
// Retrieve a single attribute from the byte buffer.
ValueSerializerPlugin valSer = session.getObjectGrid()
.getMap(map.getName()).getSerializerAccessor()
.getMapSerializerPlugin().getValueSerializerPlugin();
Object attrCtx = valSer.getAttributeContexts(attributes);
return valSer.inflateDataObjectAttributes(serValue.getContext(),
serValue.getInputStream(), attrCtx);
}
/**
* Inserts a pre-serialized key and value into the Order map.
*/
public void insertRAWOrder(Session session, byte[] key, byte[] value)
throws ObjectGridException {
ObjectMap map = session.getMap("Order");
// Get a referece to the default DataObjectContext for the map.
DataObjectContext dftDtaObjCtx = session.getObjectGrid()
.getMap(map.getName()).getSerializerAccessor()
.getDefaultContext();
// Wrap the key and value in a SerializedKey and SerializedValue
// wrapper.
SerializedKey serKey = dftDtaObjCtx.getKeyFactory().createKey(key);
SerializedValue serValue = dftDtaObjCtx.getValueFactory().createValue(
value);
// Insert the serialized form of the key and value.
map.insert(serKey, serValue);
}
}