Search in sources :

Example 6 with OTransactionException

use of com.orientechnologies.orient.core.exception.OTransactionException in project orientdb by orientechnologies.

the class OObjectEntitySerializer method toStream.

/**
   * Serialize the user POJO to a ORecordDocument instance.
   *
   * @param iPojo
   *          User pojo to serialize
   * @throws IllegalAccessException
   * @throws IllegalArgumentException
   */
@SuppressWarnings("unchecked")
protected static <T> T toStream(final T iPojo, final Proxy iProxiedPojo, ODatabaseObject db) throws IllegalArgumentException, IllegalAccessException {
    final ODocument iRecord = getDocument(iProxiedPojo);
    final long timer = Orient.instance().getProfiler().startChrono();
    final Integer identityRecord = System.identityHashCode(iPojo);
    if (OObjectSerializationThreadLocal.INSTANCE.get().containsKey(identityRecord))
        return (T) OObjectSerializationThreadLocal.INSTANCE.get().get(identityRecord);
    OObjectSerializationThreadLocal.INSTANCE.get().put(identityRecord, iProxiedPojo);
    OProperty schemaProperty;
    final Class<?> pojoClass = iPojo.getClass();
    final OClass schemaClass = iRecord.getSchemaClass();
    // CHECK FOR ID BINDING
    final Field idField = getIdField(pojoClass);
    if (idField != null) {
        Object id = getFieldValue(idField, iPojo);
        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());
        }
        if (iRecord.getIdentity().isValid() && iRecord.getIdentity().isPersistent())
            iRecord.reload();
    }
    // CHECK FOR VERSION BINDING
    final Field vField = getVersionField(pojoClass);
    boolean versionConfigured = false;
    if (vField != null) {
        versionConfigured = true;
        Object ver = getFieldValue(vField, iPojo);
        if (ver != null) {
            // FOUND
            int version = iRecord.getVersion();
            if (ver instanceof Number) {
                // TREATS AS CLUSTER POSITION
                version = ((Number) ver).intValue();
            } else if (ver instanceof String)
                version = Integer.parseInt((String) ver);
            else
                OLogManager.instance().warn(OObjectSerializerHelper.class, "@Version field has been declared as %s while the supported are: Number, String", ver.getClass());
            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");
    String fieldName;
    Object fieldValue;
    // CALL BEFORE MARSHALLING
    invokeCallback(pojoClass, iPojo, iRecord, OBeforeSerialization.class);
    Class<?> currentClass = pojoClass;
    OObjectEntitySerializedSchema serializedSchema = getCurrentSerializedSchema();
    while (!currentClass.equals(Object.class) && serializedSchema.classes.contains(pojoClass)) {
        for (Field p : getDeclaredFields(currentClass)) {
            if (Modifier.isStatic(p.getModifiers()) || Modifier.isNative(p.getModifiers()) || Modifier.isTransient(p.getModifiers()) || p.getType().isAnonymousClass())
                continue;
            fieldName = p.getName();
            List<String> classTransientFields = serializedSchema.transientFields.get(currentClass);
            if ((idField != null && fieldName.equals(idField.getName()) || (vField != null && fieldName.equals(vField.getName())) || (classTransientFields != null && classTransientFields.contains(fieldName))))
                continue;
            fieldValue = getFieldValue(p, iPojo);
            if (fieldValue != null && fieldValue.getClass().isAnonymousClass())
                continue;
            if (isSerializedType(p))
                fieldValue = serializeFieldValue(p.getType(), fieldValue);
            schemaProperty = schemaClass != null ? schemaClass.getProperty(fieldName) : null;
            OType fieldType = schemaProperty != null ? schemaProperty.getType() : getTypeByClass(currentClass, fieldName);
            if (fieldValue != null) {
                if (isEmbeddedObject(p)) {
                    // AUTO CREATE SCHEMA CLASS
                    if (iRecord.getSchemaClass() == null) {
                        db.getMetadata().getSchema().createClass(iPojo.getClass());
                        iRecord.setClassNameIfExists(iPojo.getClass().getSimpleName());
                    }
                }
            }
            fieldValue = typeToStream(fieldValue, fieldType, db, iRecord);
            iRecord.field(fieldName, fieldValue, fieldType);
        }
        currentClass = currentClass.getSuperclass();
        if (currentClass == null || currentClass.equals(ODocument.class))
            // POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER
            // ODOCUMENT FIELDS
            currentClass = Object.class;
    }
    // CALL AFTER MARSHALLING
    invokeCallback(pojoClass, iPojo, iRecord, OAfterSerialization.class);
    OObjectSerializationThreadLocal.INSTANCE.get().remove(identityRecord);
    Orient.instance().getProfiler().stopChrono("Object.toStream", "Serialize a POJO", timer);
    return (T) iProxiedPojo;
}
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) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) ProxyObject(javassist.util.proxy.ProxyObject) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) OSchemaProxyObject(com.orientechnologies.orient.object.metadata.schema.OSchemaProxyObject) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 7 with OTransactionException

use of com.orientechnologies.orient.core.exception.OTransactionException in project orientdb by orientechnologies.

the class OTxTask method execute.

@Override
public Object execute(final ODistributedRequestId requestId, final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentInternal database) throws Exception {
    ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "Executing transaction db=%s (reqId=%s)...", database.getName(), requestId);
    ODatabaseRecordThreadLocal.INSTANCE.set(database);
    final ODistributedDatabase ddb = iManager.getMessageService().getDatabase(database.getName());
    // CREATE A CONTEXT OF TX
    reqContext = ddb.registerTxContext(requestId);
    final ODistributedConfiguration dCfg = iManager.getDatabaseConfiguration(database.getName());
    result = new OTxTaskResult();
    if (tasks.size() == 0)
        // RETURN AFTER REGISTERED THE CONTEXT
        return result;
    database.begin();
    try {
        final OTransactionOptimistic tx = (OTransactionOptimistic) database.getTransaction();
        // REGISTER CREATE FIRST TO RESOLVE TEMP RIDS
        for (OAbstractRecordReplicatedTask task : tasks) {
            if (task instanceof OCreateRecordTask) {
                final OCreateRecordTask createRT = (OCreateRecordTask) task;
                final ORecordId rid = createRT.getRid();
                if (rid != null && rid.isPersistent()) {
                    if (rid.getRecord() != null)
                        // ALREADY CREATED: SKIP REGISTERING IN TX
                        continue;
                }
                final int clId = createRT.clusterId > -1 ? createRT.clusterId : createRT.getRid().isValid() ? createRT.getRid().getClusterId() : -1;
                final String clusterName = clId > -1 ? database.getClusterNameById(clId) : null;
                if (dCfg.isServerContainingCluster(iManager.getLocalNodeName(), clusterName))
                    tx.addRecord(createRT.getRecord(), ORecordOperation.CREATED, clusterName);
            }
        }
        final List<ORecordId> rids2Lock = new ArrayList<ORecordId>();
        // LOCK ALL THE RECORDS FIRST (ORDERED TO AVOID DEADLOCK)
        for (OAbstractRecordReplicatedTask task : tasks) rids2Lock.add(task.getRid());
        Collections.sort(rids2Lock);
        for (ORecordId rid : rids2Lock) reqContext.lock(rid, getRecordLock());
        for (OAbstractRecordReplicatedTask task : tasks) {
            final Object taskResult;
            // CHECK LOCAL CLUSTER IS AVAILABLE ON CURRENT SERVER
            if (!task.checkForClusterAvailability(iManager.getLocalNodeName(), dCfg))
                // SKIP EXECUTION BECAUSE THE CLUSTER IS NOT ON LOCAL NODE: THIS CAN HAPPENS IN CASE OF DISTRIBUTED TX WITH SHARDING
                taskResult = NON_LOCAL_CLUSTER;
            else {
                task.setLockRecords(false);
                task.checkRecordExists();
                taskResult = task.execute(requestId, iServer, iManager, database);
                reqContext.addUndoTask(task.getUndoTask(requestId));
            }
            result.results.add(taskResult);
        }
        database.commit();
        // SEND BACK CHANGED VALUE TO UPDATE
        for (int i = 0; i < result.results.size(); ++i) {
            final Object currentResult = result.results.get(i);
            if (currentResult == NON_LOCAL_CLUSTER)
                // SKIP IT
                continue;
            final OAbstractRecordReplicatedTask task = tasks.get(i);
            if (task instanceof OCreateRecordTask) {
                // SEND RID + VERSION
                final OCreateRecordTask t = (OCreateRecordTask) task;
                result.results.set(i, new OPlaceholder(t.getRecord()));
            } else if (task instanceof OUpdateRecordTask) {
                // SEND VERSION
                result.results.set(i, task.getRecord().getVersion());
            }
        }
        return result;
    } catch (Throwable e) {
        // if (e instanceof ODistributedRecordLockedException)
        // ddb.dumpLocks();
        ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "Rolling back transaction on local server db=%s (reqId=%s error=%s)...", database.getName(), requestId, e);
        database.rollback();
        // ddb.popTxContext(requestId);
        reqContext.unlock();
        if (!(e instanceof ONeedRetryException || e instanceof OTransactionException || e instanceof ORecordDuplicatedException || e instanceof ORecordNotFoundException))
            // DUMP ONLY GENERIC EXCEPTIONS
            ODistributedServerLog.info(this, getNodeSource(), null, DIRECTION.NONE, "Error on distributed transaction commit", e);
        return e;
    }
}
Also used : OPlaceholder(com.orientechnologies.orient.core.db.record.OPlaceholder) OAbstractRecordReplicatedTask(com.orientechnologies.orient.server.distributed.task.OAbstractRecordReplicatedTask) ArrayList(java.util.ArrayList) ORecordId(com.orientechnologies.orient.core.id.ORecordId) ONeedRetryException(com.orientechnologies.common.concur.ONeedRetryException) ORecordDuplicatedException(com.orientechnologies.orient.core.storage.ORecordDuplicatedException) OTransactionOptimistic(com.orientechnologies.orient.core.tx.OTransactionOptimistic) OTransactionException(com.orientechnologies.orient.core.exception.OTransactionException) ORecordNotFoundException(com.orientechnologies.orient.core.exception.ORecordNotFoundException)

Example 8 with OTransactionException

use of com.orientechnologies.orient.core.exception.OTransactionException in project orientdb by orientechnologies.

the class TransactionAtomicTest method testTransactionPreListenerRollback.

@Test
public void testTransactionPreListenerRollback() throws IOException {
    ODocument record1 = new ODocument();
    record1.field("value", "This is the first version").save();
    final ODatabaseListener listener = new ODatabaseListener() {

        @Override
        public void onAfterTxCommit(ODatabase iDatabase) {
        }

        @Override
        public void onAfterTxRollback(ODatabase iDatabase) {
        }

        @Override
        public void onBeforeTxBegin(ODatabase iDatabase) {
        }

        @Override
        public void onBeforeTxCommit(ODatabase iDatabase) {
            throw new RuntimeException("Rollback test");
        }

        @Override
        public void onBeforeTxRollback(ODatabase iDatabase) {
        }

        @Override
        public void onClose(ODatabase iDatabase) {
        }

        @Override
        public void onBeforeCommand(OCommandRequestText iCommand, OCommandExecutor executor) {
        }

        @Override
        public void onAfterCommand(OCommandRequestText iCommand, OCommandExecutor executor, Object result) {
        }

        @Override
        public void onCreate(ODatabase iDatabase) {
        }

        @Override
        public void onDelete(ODatabase iDatabase) {
        }

        @Override
        public void onOpen(ODatabase iDatabase) {
        }

        @Override
        public boolean onCorruptionRepairDatabase(ODatabase iDatabase, final String iReason, String iWhatWillbeFixed) {
            return true;
        }
    };
    database.registerListener(listener);
    database.begin();
    try {
        database.commit();
        Assert.assertTrue(false);
    } catch (OTransactionException e) {
        Assert.assertTrue(true);
    } finally {
        database.unregisterListener(listener);
    }
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) OCommandExecutor(com.orientechnologies.orient.core.command.OCommandExecutor) OTransactionException(com.orientechnologies.orient.core.exception.OTransactionException) ODatabase(com.orientechnologies.orient.core.db.ODatabase) ODatabaseListener(com.orientechnologies.orient.core.db.ODatabaseListener) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.testng.annotations.Test)

Example 9 with OTransactionException

use of com.orientechnologies.orient.core.exception.OTransactionException in project orientdb by orientechnologies.

the class OTransactionRealAbstract method serializeIndexChangeEntry.

protected ODocument serializeIndexChangeEntry(OTransactionIndexChangesPerKey entry, final ODocument indexDoc) {
    // SERIALIZE KEY
    ODocument keyContainer = new ODocument();
    keyContainer.setTrackingChanges(false);
    try {
        if (entry.key != null) {
            if (entry.key instanceof OCompositeKey) {
                final List<Object> keys = ((OCompositeKey) entry.key).getKeys();
                keyContainer.field("key", keys, OType.EMBEDDEDLIST);
                keyContainer.field("binary", false);
            } else if (!(entry.key instanceof ORecordElement) && (entry.key instanceof OSerializableStream)) {
                keyContainer.field("key", OStreamSerializerAnyStreamable.INSTANCE.toStream(entry.key), OType.BINARY);
                keyContainer.field("binary", true);
            } else {
                keyContainer.field("key", entry.key);
                keyContainer.field("binary", false);
            }
        } else
            keyContainer = null;
    } catch (IOException ioe) {
        throw OException.wrapException(new OTransactionException("Error during index changes serialization. "), ioe);
    }
    final List<ODocument> operations = new ArrayList<ODocument>();
    // SERIALIZE VALUES
    if (entry.entries != null && !entry.entries.isEmpty()) {
        for (OTransactionIndexEntry e : entry.entries) {
            final ODocument changeDoc = new ODocument().setAllowChainedAccess(false);
            ODocumentInternal.addOwner((ODocument) changeDoc, indexDoc);
            // SERIALIZE OPERATION
            changeDoc.field("o", e.operation.ordinal());
            if (e.value instanceof ORecord && e.value.getIdentity().isNew()) {
                final ORecord saved = getRecord(e.value.getIdentity());
                if (saved != null)
                    e.value = saved;
                else
                    ((ORecord) e.value).save();
            }
            changeDoc.field("v", e.value != null ? e.value.getIdentity() : null);
            operations.add(changeDoc);
        }
    }
    ODocument res = new ODocument();
    res.setTrackingChanges(false);
    ODocumentInternal.addOwner(res, indexDoc);
    return res.setAllowChainedAccess(false).field("k", keyContainer, OType.EMBEDDED).field("ops", operations, OType.EMBEDDEDLIST);
}
Also used : OTransactionException(com.orientechnologies.orient.core.exception.OTransactionException) ORecord(com.orientechnologies.orient.core.record.ORecord) OSerializableStream(com.orientechnologies.orient.core.serialization.OSerializableStream) IOException(java.io.IOException) OTransactionIndexEntry(com.orientechnologies.orient.core.tx.OTransactionIndexChangesPerKey.OTransactionIndexEntry) OCompositeKey(com.orientechnologies.orient.core.index.OCompositeKey) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) ORecordElement(com.orientechnologies.orient.core.db.record.ORecordElement)

Example 10 with OTransactionException

use of com.orientechnologies.orient.core.exception.OTransactionException in project orientdb by orientechnologies.

the class OrientTransactionalGraph method autoStartTransaction.

@Override
protected void autoStartTransaction() {
    final boolean txBegun = getDatabase().getTransaction().isActive();
    if (!isAutoStartTx()) {
        if (isRequireTransaction() && !txBegun)
            throw new OTransactionException("Transaction required to change the Graph");
        return;
    }
    if (!txBegun) {
        getDatabase().begin();
        getDatabase().getTransaction().setUsingLog(settings.isUseLog());
    }
}
Also used : OTransactionException(com.orientechnologies.orient.core.exception.OTransactionException)

Aggregations

OTransactionException (com.orientechnologies.orient.core.exception.OTransactionException)12 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)6 ORecordId (com.orientechnologies.orient.core.id.ORecordId)5 ORecordNotFoundException (com.orientechnologies.orient.core.exception.ORecordNotFoundException)4 ORecordOperation (com.orientechnologies.orient.core.db.record.ORecordOperation)3 ORecord (com.orientechnologies.orient.core.record.ORecord)3 OTransactionOptimistic (com.orientechnologies.orient.core.tx.OTransactionOptimistic)3 IOException (java.io.IOException)3 ONeedRetryException (com.orientechnologies.common.concur.ONeedRetryException)2 OException (com.orientechnologies.common.exception.OException)2 ODatabaseObject (com.orientechnologies.orient.core.db.object.ODatabaseObject)2 ORID (com.orientechnologies.orient.core.id.ORID)2 OCompositeKey (com.orientechnologies.orient.core.index.OCompositeKey)2 OProperty (com.orientechnologies.orient.core.metadata.schema.OProperty)2 OType (com.orientechnologies.orient.core.metadata.schema.OType)2 ORecordDuplicatedException (com.orientechnologies.orient.core.storage.ORecordDuplicatedException)2 Field (java.lang.reflect.Field)2 OCommandExecutor (com.orientechnologies.orient.core.command.OCommandExecutor)1 OCommandRequestText (com.orientechnologies.orient.core.command.OCommandRequestText)1 ODatabase (com.orientechnologies.orient.core.db.ODatabase)1