Search in sources :

Example 6 with ODatabaseObject

use of com.orientechnologies.orient.core.db.object.ODatabaseObject in project orientdb by orientechnologies.

the class OObjectSerializerHelper method toStream.

/**
 * Serialize the user POJO to a ORecordDocument instance.
 *
 * @param iPojo
 *          User pojo to serialize
 * @param iRecord
 *          Record where to update
 * @param iObj2RecHandler
 */
public static ODocument toStream(final Object iPojo, final ODocument iRecord, final OEntityManager iEntityManager, final OClass schemaClass, final OUserObject2RecordHandler iObj2RecHandler, final ODatabaseObject db, final boolean iSaveOnlyDirty) {
    if (iSaveOnlyDirty && !iRecord.isDirty())
        return iRecord;
    final long timer = Orient.instance().getProfiler().startChrono();
    final Integer identityRecord = System.identityHashCode(iRecord);
    if (OSerializationThreadLocal.INSTANCE.get().contains(identityRecord))
        return iRecord;
    OSerializationThreadLocal.INSTANCE.get().add(identityRecord);
    OProperty schemaProperty;
    final Class<?> pojoClass = iPojo.getClass();
    final List<Field> properties = getClassFields(pojoClass);
    // CHECK FOR ID BINDING
    final Field idField = fieldIds.get(pojoClass);
    if (idField != null) {
        Object id = getFieldValue(iPojo, idField.getName());
        if (id != null) {
            // FOUND
            if (id instanceof ORecordId) {
                ORecordInternal.setIdentity(iRecord, (ORecordId) id);
            } else if (id instanceof Number) {
                // TREATS AS CLUSTER POSITION
                ((ORecordId) iRecord.getIdentity()).setClusterId(schemaClass.getDefaultClusterId());
                ((ORecordId) iRecord.getIdentity()).setClusterPosition(((Number) id).longValue());
            } else if (id instanceof String)
                ((ORecordId) iRecord.getIdentity()).fromString((String) id);
            else if (id.getClass().equals(Object.class))
                ORecordInternal.setIdentity(iRecord, (ORecordId) id);
            else
                OLogManager.instance().warn(OObjectSerializerHelper.class, "@Id field has been declared as %s while the supported are: ORID, Number, String, Object", id.getClass());
        }
    }
    // CHECK FOR VERSION BINDING
    final Field vField = fieldVersions.get(pojoClass);
    boolean versionConfigured = false;
    if (vField != null) {
        versionConfigured = true;
        Object ver = getFieldValue(iPojo, vField.getName());
        final int version = convertVersion(ver);
        ORecordInternal.setVersion(iRecord, version);
    }
    if (db.isMVCC() && !versionConfigured && db.getTransaction() instanceof OTransactionOptimistic)
        throw new OTransactionException("Cannot involve an object of class '" + pojoClass + "' in an Optimistic Transaction commit because it does not define @Version or @OVersion and therefore cannot handle MVCC");
    // SET OBJECT CLASS
    iRecord.setClassName(schemaClass != null ? schemaClass.getName() : null);
    String fieldName;
    Object fieldValue;
    // CALL BEFORE MARSHALLING
    invokeCallback(iPojo, iRecord, OBeforeSerialization.class);
    for (Field p : properties) {
        fieldName = p.getName();
        if (idField != null && fieldName.equals(idField.getName()))
            continue;
        if (vField != null && fieldName.equals(vField.getName()))
            continue;
        fieldValue = serializeFieldValue(getFieldType(iPojo, fieldName), getFieldValue(iPojo, fieldName));
        schemaProperty = schemaClass != null ? schemaClass.getProperty(fieldName) : null;
        if (fieldValue != null) {
            if (isEmbeddedObject(iPojo.getClass(), fieldValue.getClass(), fieldName, iEntityManager)) {
                // AUTO CREATE SCHEMA PROPERTY
                if (schemaClass == null) {
                    db.getMetadata().getSchema().createClass(iPojo.getClass());
                    iRecord.setClassNameIfExists(iPojo.getClass().getSimpleName());
                }
                if (schemaProperty == null) {
                    OType t = OType.getTypeByClass(fieldValue.getClass());
                    if (t == null)
                        t = OType.EMBEDDED;
                    schemaProperty = iRecord.getSchemaClass().createProperty(fieldName, t);
                }
            }
        }
        fieldValue = typeToStream(fieldValue, schemaProperty != null ? schemaProperty.getType() : null, iEntityManager, iObj2RecHandler, db, iRecord, iSaveOnlyDirty);
        iRecord.field(fieldName, fieldValue);
    }
    iObj2RecHandler.registerUserObject(iPojo, iRecord);
    // CALL AFTER MARSHALLING
    invokeCallback(iPojo, iRecord, OAfterSerialization.class);
    OSerializationThreadLocal.INSTANCE.get().remove(identityRecord);
    Orient.instance().getProfiler().stopChrono("Object.toStream", "Serialize object to stream", timer);
    return iRecord;
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OType(com.orientechnologies.orient.core.metadata.schema.OType) ORecordId(com.orientechnologies.orient.core.id.ORecordId) Field(java.lang.reflect.Field) OTransactionOptimistic(com.orientechnologies.orient.core.tx.OTransactionOptimistic) OTransactionException(com.orientechnologies.orient.core.exception.OTransactionException) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject)

Example 7 with ODatabaseObject

use of com.orientechnologies.orient.core.db.object.ODatabaseObject in project orientdb by orientechnologies.

the class TestLoopEntity method testLoop.

@Test
public void testLoop() {
    ODatabaseObject object = new OObjectDatabaseTx("memory:" + TestLoopEntity.class.getSimpleName());
    object.create();
    try {
        object.getEntityManager().registerEntityClasses(LoopEntity.class, true);
        assertTrue(object.getMetadata().getSchema().existsClass("LoopEntity"));
        assertTrue(object.getMetadata().getSchema().existsClass("LoopEntityLink"));
    } finally {
        object.drop();
    }
}
Also used : ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) Test(org.junit.Test)

Example 8 with ODatabaseObject

use of com.orientechnologies.orient.core.db.object.ODatabaseObject in project orientdb by orientechnologies.

the class ORecordSerializerCSVAbstract method embeddedMapToStream.

public void embeddedMapToStream(ODatabase<?> iDatabase, final OUserObject2RecordHandler iObjHandler, final StringBuilder iOutput, final OClass iLinkedClass, OType iLinkedType, final Object iValue, final boolean iSaveOnlyDirty) {
    iOutput.append(OStringSerializerHelper.MAP_BEGIN);
    if (iValue != null) {
        int items = 0;
        // EMBEDDED OBJECTS
        for (Entry<String, Object> o : ((Map<String, Object>) iValue).entrySet()) {
            if (items > 0)
                iOutput.append(OStringSerializerHelper.RECORD_SEPARATOR);
            if (o != null) {
                fieldTypeToString(iOutput, OType.STRING, o.getKey());
                iOutput.append(OStringSerializerHelper.ENTRY_SEPARATOR);
                if (o.getValue() instanceof ODocument && ((ODocument) o.getValue()).getIdentity().isValid()) {
                    fieldTypeToString(iOutput, OType.LINK, o.getValue());
                } else if (o.getValue() instanceof ORecord || o.getValue() instanceof ODocumentSerializable) {
                    final ODocument record;
                    if (o.getValue() instanceof ODocument)
                        record = (ODocument) o.getValue();
                    else if (o.getValue() instanceof ODocumentSerializable) {
                        record = ((ODocumentSerializable) o.getValue()).toDocument();
                        record.field(ODocumentSerializable.CLASS_NAME, o.getValue().getClass().getName());
                    } else {
                        if (iDatabase == null && ODatabaseRecordThreadLocal.INSTANCE.isDefined())
                            iDatabase = ODatabaseRecordThreadLocal.INSTANCE.get();
                        record = OObjectSerializerHelperManager.getInstance().toStream(o.getValue(), new ODocument(o.getValue().getClass().getSimpleName()), iDatabase instanceof ODatabaseObject ? ((ODatabaseObject) iDatabase).getEntityManager() : OEntityManagerInternal.INSTANCE, iLinkedClass, iObjHandler != null ? iObjHandler : new OUserObject2RecordHandler() {

                            public Object getUserObjectByRecord(OIdentifiable iRecord, final String iFetchPlan) {
                                return iRecord;
                            }

                            public ORecord getRecordByUserObject(Object iPojo, boolean iCreateIfNotAvailable) {
                                return new ODocument(iLinkedClass);
                            }

                            public boolean existsUserObjectByRID(ORID iRID) {
                                return false;
                            }

                            public void registerUserObject(Object iObject, ORecord iRecord) {
                            }

                            public void registerUserObjectAfterLinkSave(ORecord iRecord) {
                            }
                        }, null, iSaveOnlyDirty);
                    }
                    iOutput.append(OStringSerializerHelper.EMBEDDED_BEGIN);
                    toString(record, iOutput, null, iObjHandler, false, true);
                    iOutput.append(OStringSerializerHelper.EMBEDDED_END);
                } else if (o.getValue() instanceof Set<?>) {
                    // SUB SET
                    fieldTypeToString(iOutput, OType.EMBEDDEDSET, o.getValue());
                } else if (o.getValue() instanceof Collection<?>) {
                    // SUB LIST
                    fieldTypeToString(iOutput, OType.EMBEDDEDLIST, o.getValue());
                } else if (o.getValue() instanceof Map<?, ?>) {
                    // SUB MAP
                    fieldTypeToString(iOutput, OType.EMBEDDEDMAP, o.getValue());
                } else {
                    // EMBEDDED LITERALS
                    if (iLinkedType == null && o.getValue() != null) {
                        fieldTypeToString(iOutput, OType.getTypeByClass(o.getValue().getClass()), o.getValue());
                    } else {
                        fieldTypeToString(iOutput, iLinkedType, o.getValue());
                    }
                }
            }
            items++;
        }
    }
    iOutput.append(OStringSerializerHelper.MAP_END);
}
Also used : OTrackedSet(com.orientechnologies.orient.core.db.record.OTrackedSet) Set(java.util.Set) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) ORecord(com.orientechnologies.orient.core.record.ORecord) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) ODocumentSerializable(com.orientechnologies.orient.core.serialization.ODocumentSerializable) OUserObject2RecordHandler(com.orientechnologies.orient.core.db.OUserObject2RecordHandler) ORID(com.orientechnologies.orient.core.id.ORID) OTrackedMap(com.orientechnologies.orient.core.db.record.OTrackedMap) ORecordLazyMap(com.orientechnologies.orient.core.db.record.ORecordLazyMap) Map(java.util.Map) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 9 with ODatabaseObject

use of com.orientechnologies.orient.core.db.object.ODatabaseObject in project orientdb by orientechnologies.

the class OObjectEntitySerializer method multiValueToStream.

@SuppressWarnings("unchecked")
private static Object multiValueToStream(final Object iMultiValue, OType iType, final ODatabaseObject db, final ODocument iRecord) {
    if (iMultiValue == null)
        return null;
    final Collection<Object> sourceValues;
    if (iMultiValue instanceof Collection<?>) {
        sourceValues = (Collection<Object>) iMultiValue;
    } else {
        sourceValues = (Collection<Object>) ((Map<?, ?>) iMultiValue).values();
    }
    if (sourceValues.size() == 0)
        return iMultiValue;
    // TRY TO UNDERSTAND THE COLLECTION TYPE BY ITS CONTENT
    final Object firstValue = sourceValues.iterator().next();
    if (firstValue == null)
        return iMultiValue;
    if (iType == null) {
        // DETERMINE THE RIGHT TYPE BASED ON SOURCE MULTI VALUE OBJECT
        if (OType.isSimpleType(firstValue)) {
            if (iMultiValue instanceof List)
                iType = OType.EMBEDDEDLIST;
            else if (iMultiValue instanceof Set)
                iType = OType.EMBEDDEDSET;
            else
                iType = OType.EMBEDDEDMAP;
        } else {
            if (iMultiValue instanceof List)
                iType = OType.LINKLIST;
            else if (iMultiValue instanceof Set)
                iType = OType.LINKSET;
            else
                iType = OType.LINKMAP;
        }
    }
    Object result = iMultiValue;
    final OType linkedType;
    // CREATE THE RETURN MULTI VALUE OBJECT BASED ON DISCOVERED TYPE
    if (iType.equals(OType.EMBEDDEDSET) || iType.equals(OType.LINKSET)) {
        if (isToSerialize(firstValue.getClass()))
            result = new HashSet<Object>();
        else if ((iRecord != null && iType.equals(OType.EMBEDDEDSET)) || OType.isSimpleType(firstValue))
            result = new OTrackedSet<Object>(iRecord);
        else
            result = new ORecordLazySet(iRecord);
    } else if (iType.equals(OType.EMBEDDEDLIST) || iType.equals(OType.LINKLIST)) {
        if (isToSerialize(firstValue.getClass()))
            result = new ArrayList<Object>();
        else if ((iRecord != null && iType.equals(OType.EMBEDDEDLIST)) || OType.isSimpleType(firstValue))
            result = new OTrackedList<Object>(iRecord);
        else
            result = new ORecordLazyList(iRecord);
    }
    if (iType.equals(OType.LINKLIST) || iType.equals(OType.LINKSET) || iType.equals(OType.LINKMAP))
        linkedType = OType.LINK;
    else if (iType.equals(OType.EMBEDDEDLIST) || iType.equals(OType.EMBEDDEDSET) || iType.equals(OType.EMBEDDEDMAP))
        if (firstValue instanceof List)
            linkedType = OType.EMBEDDEDLIST;
        else if (firstValue instanceof Set)
            linkedType = OType.EMBEDDEDSET;
        else if (firstValue instanceof Map)
            linkedType = OType.EMBEDDEDMAP;
        else
            linkedType = OType.EMBEDDED;
    else
        throw new IllegalArgumentException("Type " + iType + " must be a multi value type (collection or map)");
    if (iMultiValue instanceof Set<?>) {
        for (Object o : sourceValues) {
            ((Set<Object>) result).add(typeToStream(o, linkedType, db, iRecord));
        }
    } else if (iMultiValue instanceof List<?>) {
        for (int i = 0; i < sourceValues.size(); i++) {
            ((List<Object>) result).add(typeToStream(((List<?>) sourceValues).get(i), linkedType, db, iRecord));
        }
    } else {
        if (iMultiValue instanceof OObjectLazyMap<?>) {
            result = ((OObjectLazyMap<?>) iMultiValue).getUnderlying();
        } else {
            if (isToSerialize(firstValue.getClass()))
                result = new HashMap<Object, Object>();
            else if (iRecord != null && iType.equals(OType.EMBEDDEDMAP))
                result = new OTrackedMap<Object>(iRecord);
            else
                result = new ORecordLazyMap(iRecord);
            for (Entry<Object, Object> entry : ((Map<Object, Object>) iMultiValue).entrySet()) {
                ((Map<Object, Object>) result).put(entry.getKey(), typeToStream(entry.getValue(), linkedType, db, iRecord));
            }
        }
    }
    return result;
}
Also used : OObjectLazyMap(com.orientechnologies.orient.object.db.OObjectLazyMap) ORecordLazyList(com.orientechnologies.orient.core.db.record.ORecordLazyList) Set(java.util.Set) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) HashSet(java.util.HashSet) OTrackedSet(com.orientechnologies.orient.core.db.record.OTrackedSet) OType(com.orientechnologies.orient.core.metadata.schema.OType) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) ORecordLazyMap(com.orientechnologies.orient.core.db.record.ORecordLazyMap) Entry(java.util.Map.Entry) OTrackedList(com.orientechnologies.orient.core.db.record.OTrackedList) OTrackedMap(com.orientechnologies.orient.core.db.record.OTrackedMap) Collection(java.util.Collection) ProxyObject(javassist.util.proxy.ProxyObject) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) OSchemaProxyObject(com.orientechnologies.orient.object.metadata.schema.OSchemaProxyObject) List(java.util.List) ORecordLazyList(com.orientechnologies.orient.core.db.record.ORecordLazyList) ArrayList(java.util.ArrayList) OTrackedList(com.orientechnologies.orient.core.db.record.OTrackedList) ORecordLazyMap(com.orientechnologies.orient.core.db.record.ORecordLazyMap) Map(java.util.Map) OTrackedMap(com.orientechnologies.orient.core.db.record.OTrackedMap) HashMap(java.util.HashMap) OObjectLazyMap(com.orientechnologies.orient.object.db.OObjectLazyMap) HashSet(java.util.HashSet)

Example 10 with ODatabaseObject

use of com.orientechnologies.orient.core.db.object.ODatabaseObject in project orientdb by orientechnologies.

the class OObjectEntityEnhancer method getProxiedInstance.

@SuppressWarnings("unchecked")
public <T> T getProxiedInstance(final Class<T> iClass, Object iEnclosingInstance, final ODocument doc, final ProxyObject parent, Object... iArgs) {
    if (iClass == null) {
        throw new OSerializationException("Type '" + doc.getClassName() + "' cannot be serialized because is not part of registered entities. To fix this error register this class");
    }
    final Class<T> c;
    boolean isInnerClass = OObjectEntitySerializer.getEnclosingClass(iClass) != null;
    if (Proxy.class.isAssignableFrom(iClass)) {
        c = iClass;
    } else {
        ProxyFactory f = new ProxyFactory();
        f.setSuperclass(iClass);
        if (customMethodFilters.get(iClass) != null) {
            f.setFilter(customMethodFilters.get(iClass));
        } else {
            f.setFilter(defaultMethodFilter);
        }
        c = f.createClass();
    }
    MethodHandler mi = new OObjectProxyMethodHandler(doc);
    ((OObjectProxyMethodHandler) mi).setParentObject(parent);
    try {
        T newEntity;
        if (iArgs != null && iArgs.length > 0) {
            if (isInnerClass) {
                if (iEnclosingInstance == null) {
                    iEnclosingInstance = iClass.getEnclosingClass().newInstance();
                }
                Object[] newArgs = new Object[iArgs.length + 1];
                newArgs[0] = iEnclosingInstance;
                for (int i = 0; i < iArgs.length; i++) {
                    newArgs[i + 1] = iArgs[i];
                }
                iArgs = newArgs;
            }
            Constructor<T> constructor = null;
            for (Constructor<?> constr : c.getConstructors()) {
                boolean found = true;
                if (constr.getParameterTypes().length == iArgs.length) {
                    for (int i = 0; i < constr.getParameterTypes().length; i++) {
                        Class<?> parameterType = constr.getParameterTypes()[i];
                        if (parameterType.isPrimitive()) {
                            if (!isPrimitiveParameterCorrect(parameterType, iArgs[i])) {
                                found = false;
                                break;
                            }
                        } else if (iArgs[i] != null && !parameterType.isAssignableFrom(iArgs[i].getClass())) {
                            found = false;
                            break;
                        }
                    }
                } else {
                    continue;
                }
                if (found) {
                    constructor = (Constructor<T>) constr;
                    break;
                }
            }
            if (constructor != null) {
                newEntity = (T) constructor.newInstance(iArgs);
                initDocument(iClass, newEntity, doc, (ODatabaseObject) ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner());
            } else {
                if (iEnclosingInstance != null)
                    newEntity = createInstanceNoParameters(c, iEnclosingInstance);
                else
                    newEntity = createInstanceNoParameters(c, iClass);
            }
        } else {
            if (iEnclosingInstance != null)
                newEntity = createInstanceNoParameters(c, iEnclosingInstance);
            else
                newEntity = createInstanceNoParameters(c, iClass);
        }
        ((Proxy) newEntity).setHandler(mi);
        if (OObjectEntitySerializer.hasBoundedDocumentField(iClass))
            OObjectEntitySerializer.setFieldValue(OObjectEntitySerializer.getBoundedDocumentField(iClass), newEntity, doc);
        OObjectEntitySerializer.setVersionField(iClass, newEntity, doc.getVersion());
        return newEntity;
    } catch (InstantiationException ie) {
        OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), ie);
    } catch (IllegalAccessException iae) {
        OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), iae);
    } catch (IllegalArgumentException iae) {
        OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), iae);
    } catch (SecurityException se) {
        OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), se);
    } catch (InvocationTargetException ite) {
        OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), ite);
    } catch (NoSuchMethodException nsme) {
        OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), nsme);
    }
    return null;
}
Also used : OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) ProxyFactory(javassist.util.proxy.ProxyFactory) InvocationTargetException(java.lang.reflect.InvocationTargetException) MethodHandler(javassist.util.proxy.MethodHandler) Proxy(javassist.util.proxy.Proxy) ProxyObject(javassist.util.proxy.ProxyObject) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject)

Aggregations

ODatabaseObject (com.orientechnologies.orient.core.db.object.ODatabaseObject)12 OType (com.orientechnologies.orient.core.metadata.schema.OType)7 Set (java.util.Set)6 ProxyObject (javassist.util.proxy.ProxyObject)6 ORecordLazySet (com.orientechnologies.orient.core.db.record.ORecordLazySet)5 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)5 Map (java.util.Map)5 OTrackedSet (com.orientechnologies.orient.core.db.record.OTrackedSet)4 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)4 ORecord (com.orientechnologies.orient.core.record.ORecord)4 ArrayList (java.util.ArrayList)4 HashSet (java.util.HashSet)4 List (java.util.List)4 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)3 ORecordLazyMap (com.orientechnologies.orient.core.db.record.ORecordLazyMap)3 OTrackedList (com.orientechnologies.orient.core.db.record.OTrackedList)3 OTrackedMap (com.orientechnologies.orient.core.db.record.OTrackedMap)3 ORID (com.orientechnologies.orient.core.id.ORID)3 OProperty (com.orientechnologies.orient.core.metadata.schema.OProperty)3 Field (java.lang.reflect.Field)3