use of org.qi4j.api.type.ValueType in project qi4j-sdk by Qi4j.
the class PreferencesEntityStoreMixin method writeEntityState.
protected void writeEntityState(DefaultEntityState state, Preferences entityPrefs, String identity, long lastModified) throws EntityStoreException {
try {
// Store into Preferences API
entityPrefs.put("type", first(state.entityDescriptor().types()).getName());
entityPrefs.put("version", identity);
entityPrefs.putLong("modified", lastModified);
// Properties
Preferences propsPrefs = entityPrefs.node("properties");
for (PropertyDescriptor persistentProperty : state.entityDescriptor().state().properties()) {
if (persistentProperty.qualifiedName().name().equals("identity")) {
// Skip Identity.identity()
continue;
}
Object value = state.properties().get(persistentProperty.qualifiedName());
if (value == null) {
propsPrefs.remove(persistentProperty.qualifiedName().name());
} else {
ValueType valueType = persistentProperty.valueType();
Class<?> mainType = valueType.mainType();
if (Number.class.isAssignableFrom(mainType)) {
if (mainType.equals(Long.class)) {
propsPrefs.putLong(persistentProperty.qualifiedName().name(), (Long) value);
} else if (mainType.equals(Integer.class)) {
propsPrefs.putInt(persistentProperty.qualifiedName().name(), (Integer) value);
} else if (mainType.equals(Double.class)) {
propsPrefs.putDouble(persistentProperty.qualifiedName().name(), (Double) value);
} else if (mainType.equals(Float.class)) {
propsPrefs.putFloat(persistentProperty.qualifiedName().name(), (Float) value);
} else {
// Store as string even though it's a number
String jsonString = valueSerialization.serialize(value);
propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
}
} else if (mainType.equals(Boolean.class)) {
propsPrefs.putBoolean(persistentProperty.qualifiedName().name(), (Boolean) value);
} else if (valueType instanceof ValueCompositeType || valueType instanceof MapType || valueType instanceof CollectionType || valueType instanceof EnumType) {
String jsonString = valueSerialization.serialize(value);
propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
} else {
String jsonString = valueSerialization.serialize(value);
propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
}
}
}
// Associations
if (!state.associations().isEmpty()) {
Preferences assocsPrefs = entityPrefs.node("associations");
for (Map.Entry<QualifiedName, EntityReference> association : state.associations().entrySet()) {
if (association.getValue() == null) {
assocsPrefs.remove(association.getKey().name());
} else {
assocsPrefs.put(association.getKey().name(), association.getValue().identity());
}
}
}
// ManyAssociations
if (!state.manyAssociations().isEmpty()) {
Preferences manyAssocsPrefs = entityPrefs.node("manyassociations");
for (Map.Entry<QualifiedName, List<EntityReference>> manyAssociations : state.manyAssociations().entrySet()) {
StringBuilder manyAssocs = new StringBuilder();
for (EntityReference entityReference : manyAssociations.getValue()) {
if (manyAssocs.length() > 0) {
manyAssocs.append("\n");
}
manyAssocs.append(entityReference.identity());
}
if (manyAssocs.length() > 0) {
manyAssocsPrefs.put(manyAssociations.getKey().name(), manyAssocs.toString());
}
}
}
} catch (ValueSerializationException e) {
throw new EntityStoreException("Could not store EntityState", e);
}
}
use of org.qi4j.api.type.ValueType in project qi4j-sdk by Qi4j.
the class PreferencesEntityStoreMixin method entityStateOf.
@Override
public EntityState entityStateOf(EntityStoreUnitOfWork unitOfWork, EntityReference identity) {
try {
DefaultEntityStoreUnitOfWork desuw = (DefaultEntityStoreUnitOfWork) unitOfWork;
Module module = desuw.module();
if (!root.nodeExists(identity.identity())) {
throw new NoSuchEntityException(identity);
}
Preferences entityPrefs = root.node(identity.identity());
String type = entityPrefs.get("type", null);
EntityStatus status = EntityStatus.LOADED;
EntityDescriptor entityDescriptor = module.entityDescriptor(type);
if (entityDescriptor == null) {
throw new EntityTypeNotFoundException(type);
}
Map<QualifiedName, Object> properties = new HashMap<QualifiedName, Object>();
Preferences propsPrefs = null;
for (PropertyDescriptor persistentPropertyDescriptor : entityDescriptor.state().properties()) {
if (persistentPropertyDescriptor.qualifiedName().name().equals("identity")) {
// Fake identity property
properties.put(persistentPropertyDescriptor.qualifiedName(), identity.identity());
continue;
}
if (propsPrefs == null) {
propsPrefs = entityPrefs.node("properties");
}
ValueType propertyType = persistentPropertyDescriptor.valueType();
Class<?> mainType = propertyType.mainType();
if (Number.class.isAssignableFrom(mainType)) {
if (mainType.equals(Long.class)) {
properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, new NumberParser<Long>() {
@Override
public Long parse(String str) {
return Long.parseLong(str);
}
}));
} else if (mainType.equals(Integer.class)) {
properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, new NumberParser<Integer>() {
@Override
public Integer parse(String str) {
return Integer.parseInt(str);
}
}));
} else if (mainType.equals(Double.class)) {
properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, new NumberParser<Double>() {
@Override
public Double parse(String str) {
return Double.parseDouble(str);
}
}));
} else if (mainType.equals(Float.class)) {
properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, new NumberParser<Float>() {
@Override
public Float parse(String str) {
return Float.parseFloat(str);
}
}));
} else {
// Load as string even though it's a number
String json = propsPrefs.get(persistentPropertyDescriptor.qualifiedName().name(), null);
Object value;
if (json == null) {
value = null;
} else {
value = valueSerialization.deserialize(persistentPropertyDescriptor.valueType(), json);
}
properties.put(persistentPropertyDescriptor.qualifiedName(), value);
}
} else if (mainType.equals(Boolean.class)) {
Boolean initialValue = (Boolean) persistentPropertyDescriptor.initialValue(module);
properties.put(persistentPropertyDescriptor.qualifiedName(), propsPrefs.getBoolean(persistentPropertyDescriptor.qualifiedName().name(), initialValue == null ? false : initialValue));
} else if (propertyType instanceof ValueCompositeType || propertyType instanceof MapType || propertyType instanceof CollectionType || propertyType instanceof EnumType) {
String json = propsPrefs.get(persistentPropertyDescriptor.qualifiedName().name(), null);
Object value;
if (json == null) {
value = null;
} else {
value = valueSerialization.deserialize(persistentPropertyDescriptor.valueType(), json);
}
properties.put(persistentPropertyDescriptor.qualifiedName(), value);
} else {
String json = propsPrefs.get(persistentPropertyDescriptor.qualifiedName().name(), null);
if (json == null) {
if (persistentPropertyDescriptor.initialValue(module) != null) {
properties.put(persistentPropertyDescriptor.qualifiedName(), persistentPropertyDescriptor.initialValue(module));
} else {
properties.put(persistentPropertyDescriptor.qualifiedName(), null);
}
} else {
Object value = valueSerialization.deserialize(propertyType, json);
properties.put(persistentPropertyDescriptor.qualifiedName(), value);
}
}
}
// Associations
Map<QualifiedName, EntityReference> associations = new HashMap<QualifiedName, EntityReference>();
Preferences assocs = null;
for (AssociationDescriptor associationType : entityDescriptor.state().associations()) {
if (assocs == null) {
assocs = entityPrefs.node("associations");
}
String associatedEntity = assocs.get(associationType.qualifiedName().name(), null);
EntityReference value = associatedEntity == null ? null : EntityReference.parseEntityReference(associatedEntity);
associations.put(associationType.qualifiedName(), value);
}
// ManyAssociations
Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<QualifiedName, List<EntityReference>>();
Preferences manyAssocs = null;
for (AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations()) {
if (manyAssocs == null) {
manyAssocs = entityPrefs.node("manyassociations");
}
List<EntityReference> references = new ArrayList<EntityReference>();
String entityReferences = manyAssocs.get(manyAssociationType.qualifiedName().name(), null);
if (entityReferences == null) {
// ManyAssociation not found, default to empty one
manyAssociations.put(manyAssociationType.qualifiedName(), references);
} else {
String[] refs = entityReferences.split("\n");
for (String ref : refs) {
EntityReference value = ref == null ? null : EntityReference.parseEntityReference(ref);
references.add(value);
}
manyAssociations.put(manyAssociationType.qualifiedName(), references);
}
}
return new DefaultEntityState(desuw, entityPrefs.get("version", ""), entityPrefs.getLong("modified", unitOfWork.currentTime()), identity, status, entityDescriptor, properties, associations, manyAssociations);
} catch (ValueSerializationException e) {
throw new EntityStoreException(e);
} catch (BackingStoreException e) {
throw new EntityStoreException(e);
}
}
use of org.qi4j.api.type.ValueType in project qi4j-sdk by Qi4j.
the class EntityStateSerializer method serializeProperty.
private void serializeProperty(PropertyDescriptor persistentProperty, Object property, Resource subject, Graph graph, boolean includeNonQueryable) {
if (!(includeNonQueryable || persistentProperty.queryable())) {
// Skip non-queryable
return;
}
ValueType valueType = persistentProperty.valueType();
final ValueFactory valueFactory = graph.getValueFactory();
String propertyURI = persistentProperty.qualifiedName().toURI();
URI predicate = valueFactory.createURI(propertyURI);
String baseURI = propertyURI.substring(0, propertyURI.indexOf('#')) + "/";
if (valueType instanceof ValueCompositeType) {
serializeValueComposite(subject, predicate, (ValueComposite) property, valueType, graph, baseURI, includeNonQueryable);
} else {
String stringProperty = valueSerializer.serialize(property, false);
final Literal object = valueFactory.createLiteral(stringProperty);
graph.add(subject, predicate, object);
}
}
use of org.qi4j.api.type.ValueType in project qi4j-sdk by Qi4j.
the class ValueDeserializerAdapter method deserializeValueComposite.
private <T> T deserializeValueComposite(ValueCompositeType valueCompositeType, Class<?> valueBuilderType, InputNodeType inputNode) throws Exception {
final Map<String, Object> stateMap = new HashMap<String, Object>();
// Properties
for (PropertyDescriptor property : valueCompositeType.properties()) {
String propertyName = property.qualifiedName().name();
Object value;
if (objectHasField(inputNode, propertyName)) {
value = getObjectFieldValue(inputNode, propertyName, buildDeserializeInputNodeFunction(property.valueType()));
TREE_PARSING_LOG.trace("In deserializeValueComposite(), getObjectFieldValue( {} ) for key {} returned '{}' of class {}", inputNode, propertyName, value, value == null ? "N/A" : value.getClass());
if (property.isImmutable()) {
if (value instanceof Set) {
value = Collections.unmodifiableSet((Set<?>) value);
} else if (value instanceof List) {
value = Collections.unmodifiableList((List<?>) value);
} else if (value instanceof Map) {
value = Collections.unmodifiableMap((Map<?, ?>) value);
}
}
TREE_PARSING_LOG.trace("Property {}#{}( {} ) deserialized value is '{}' of class {}", property.qualifiedName().type(), property.qualifiedName().name(), property.valueType(), value, value == null ? "N/A" : value.getClass());
} else {
// Serialized object does not contain the field, try to default it
value = property.initialValue(valuesModule());
TREE_PARSING_LOG.trace("Property {} was not defined in serialized object and has been defaulted to '{}'", property.qualifiedName(), value);
}
stateMap.put(propertyName, value);
}
// Associations
for (AssociationDescriptor association : valueCompositeType.associations()) {
String associationName = association.qualifiedName().name();
if (objectHasField(inputNode, associationName)) {
Object value = getObjectFieldValue(inputNode, associationName, buildDeserializeInputNodeFunction(new ValueType(EntityReference.class)));
stateMap.put(associationName, value);
}
}
// ManyAssociations
for (AssociationDescriptor manyAssociation : valueCompositeType.manyAssociations()) {
String manyAssociationName = manyAssociation.qualifiedName().name();
if (objectHasField(inputNode, manyAssociationName)) {
Object value = getObjectFieldValue(inputNode, manyAssociationName, buildDeserializeInputNodeFunction(new CollectionType(Collection.class, new ValueType(EntityReference.class))));
stateMap.put(manyAssociationName, value);
}
}
ValueBuilder<?> valueBuilder = buildNewValueBuilderWithState(valueBuilderType, stateMap);
// Unchecked cast because the builder could use a type != T
return (T) valueBuilder.newInstance();
}
use of org.qi4j.api.type.ValueType in project qi4j-sdk by Qi4j.
the class AbstractCollectionSerializationTest method givenCollectionTypeWithBigIntegerAndNullElementWhenSerializingAndDeserializingExpectEquals.
@Test
public void givenCollectionTypeWithBigIntegerAndNullElementWhenSerializingAndDeserializingExpectEquals() throws Exception {
String output = valueSerialization.serialize(bigIntegerCollection());
CollectionType collectionType = new CollectionType(List.class, new ValueType(BigInteger.class));
List<BigInteger> list = valueSerialization.deserialize(collectionType, output);
assertEquals(bigIntegerCollection(), list);
}
Aggregations