Search in sources :

Example 31 with OSerializationException

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

the class OJSONWriter method listToJSON.

public static String listToJSON(final Collection<? extends OIdentifiable> iRecords, final String iFormat) {
    try {
        final StringWriter buffer = new StringWriter();
        final OJSONWriter json = new OJSONWriter(buffer);
        // WRITE RECORDS
        json.beginCollection(0, false, null);
        if (iRecords != null) {
            if (iFormat != null && iFormat.contains("shallow")) {
                buffer.append("" + iRecords.size());
            } else {
                int counter = 0;
                String objectJson;
                for (OIdentifiable rec : iRecords) {
                    if (rec != null)
                        try {
                            objectJson = iFormat != null ? rec.getRecord().toJSON(iFormat) : rec.getRecord().toJSON();
                            if (counter++ > 0)
                                buffer.append(",");
                            buffer.append(objectJson);
                        } catch (Exception e) {
                            OLogManager.instance().error(json, "Error transforming record " + rec.getIdentity() + " to JSON", e);
                        }
                }
            }
        }
        json.endCollection(0, false);
        return buffer.toString();
    } catch (IOException e) {
        throw OException.wrapException(new OSerializationException("Error on serializing collection"), e);
    }
}
Also used : OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OException(com.orientechnologies.common.exception.OException) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException)

Example 32 with OSerializationException

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

the class ORecordSerializerNetworkV0 method serialize.

@SuppressWarnings("unchecked")
@Override
public void serialize(final ODocument document, final BytesContainer bytes, final boolean iClassOnly) {
    final OClass clazz = serializeClass(document, bytes);
    if (iClassOnly) {
        writeEmptyString(bytes);
        return;
    }
    final Set<Entry<String, ODocumentEntry>> fields = ODocumentInternal.rawEntries(document);
    final int[] pos = new int[fields.size()];
    int i = 0;
    final Entry<String, ODocumentEntry>[] values = new Entry[fields.size()];
    for (Entry<String, ODocumentEntry> entry : fields) {
        ODocumentEntry docEntry = entry.getValue();
        if (!docEntry.exist())
            continue;
        writeString(bytes, entry.getKey());
        pos[i] = bytes.alloc(OIntegerSerializer.INT_SIZE + 1);
        values[i] = entry;
        i++;
    }
    writeEmptyString(bytes);
    int size = i;
    for (i = 0; i < size; i++) {
        int pointer = 0;
        final Object value = values[i].getValue().value;
        if (value != null) {
            final OType type = getFieldType(values[i].getValue());
            if (type == null) {
                throw new OSerializationException("Impossible serialize value of type " + value.getClass() + " with the ODocument binary serializer");
            }
            pointer = serializeValue(bytes, value, type, getLinkedType(document, type, values[i].getKey()));
            OIntegerSerializer.INSTANCE.serializeLiteral(pointer, bytes.bytes, pos[i]);
            writeOType(bytes, (pos[i] + OIntegerSerializer.INT_SIZE), type);
        }
    }
}
Also used : ODocumentEntry(com.orientechnologies.orient.core.record.impl.ODocumentEntry) Entry(java.util.Map.Entry) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OType(com.orientechnologies.orient.core.metadata.schema.OType) ODocumentEntry(com.orientechnologies.orient.core.record.impl.ODocumentEntry)

Example 33 with OSerializationException

use of com.orientechnologies.orient.core.exception.OSerializationException 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)

Example 34 with OSerializationException

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

the class OTransactionOptimisticProxy method begin.

@Override
public void begin() {
    super.begin();
    // Needed for keep the exception and insure that all data is read from the socket.
    OException toThrow = null;
    try {
        setUsingLog(channel.readByte() == 1);
        Map<ORecord, byte[]> lazyDeserialize = new IdentityHashMap<ORecord, byte[]>();
        byte lastTxStatus;
        for (lastTxStatus = channel.readByte(); lastTxStatus == 1; lastTxStatus = channel.readByte()) {
            final byte recordStatus = channel.readByte();
            final ORecordId rid = channel.readRID();
            final byte recordType = channel.readByte();
            final ORecordOperation entry = new OTransactionEntryProxy(recordType);
            entry.type = recordStatus;
            switch(recordStatus) {
                case ORecordOperation.CREATED:
                    byte[] content = channel.readBytes();
                    ORecordInternal.fill(entry.getRecord(), rid, 0, null, true);
                    // oNetworkProtocolBinary.fillRecord(rid, content, 0, entry.getRecord(), database);
                    lazyDeserialize.put(entry.getRecord(), content);
                    // SAVE THE RECORD TO RETRIEVE THEM FOR THE NEW RID TO SEND BACK TO THE REQUESTER
                    createdRecords.put(rid.copy(), entry.getRecord());
                    break;
                case ORecordOperation.UPDATED:
                    int version = channel.readVersion();
                    byte[] bytes = channel.readBytes();
                    ORecordInternal.fill(entry.getRecord(), rid, version, null, true);
                    // oNetworkProtocolBinary.fillRecord(rid, bytes, version, entry.getRecord(), database);
                    lazyDeserialize.put(entry.getRecord(), bytes);
                    if (protocolVersion >= 23)
                        ORecordInternal.setContentChanged(entry.getRecord(), channel.readBoolean());
                    break;
                case ORecordOperation.DELETED:
                    // LOAD RECORD TO BE SURE IT HASN'T BEEN DELETED BEFORE + PROVIDE CONTENT FOR ANY HOOK
                    final ORecord rec = rid.getRecord();
                    int deleteVersion = channel.readVersion();
                    if (rec == null)
                        toThrow = new ORecordNotFoundException(rid);
                    else {
                        ORecordInternal.setVersion(rec, deleteVersion);
                        entry.setRecord(rec);
                    }
                    break;
                default:
                    throw new OTransactionException("Unrecognized tx command: " + recordStatus);
            }
            // PUT IN TEMPORARY LIST TO GET FETCHED AFTER ALL FOR CACHE
            tempEntries.put(entry.getRecord().getIdentity(), entry);
        }
        String dbSerializerName = "";
        if (database != null)
            dbSerializerName = database.getSerializer().toString();
        String name = oNetworkProtocolBinary.getRecordSerializerName(connection);
        for (Map.Entry<ORecord, byte[]> entry : lazyDeserialize.entrySet()) {
            ORecord record = entry.getKey();
            final boolean contentChanged = ORecordInternal.isContentChanged(record);
            if (ORecordInternal.getRecordType(record) == ODocument.RECORD_TYPE && !dbSerializerName.equals(name)) {
                ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(name);
                ser.fromStream(entry.getValue(), record, null);
                record.setDirty();
                ORecordInternal.setContentChanged(record, contentChanged);
            } else {
                record.fromStream(entry.getValue());
                record.setDirty();
                ORecordInternal.setContentChanged(record, contentChanged);
            }
        }
        if (toThrow != null)
            throw toThrow;
        if (lastTxStatus == -1)
            // ABORT TX
            throw new OTransactionAbortedException("Transaction aborted by the client");
        final ODocument remoteIndexEntries = new ODocument(channel.readBytes());
        fillIndexOperations(remoteIndexEntries);
        // FIRE THE TRIGGERS ONLY AFTER HAVING PARSED THE REQUEST
        for (Entry<ORID, ORecordOperation> entry : tempEntries.entrySet()) {
            if (entry.getValue().type == ORecordOperation.UPDATED) {
                // SPECIAL CASE FOR UPDATE: WE NEED TO LOAD THE RECORD AND APPLY CHANGES TO GET WORKING HOOKS (LIKE INDEXES)
                final ORecord record = entry.getValue().record.getRecord();
                final boolean contentChanged = ORecordInternal.isContentChanged(record);
                final ORecord loadedRecord = record.getIdentity().copy().getRecord();
                if (loadedRecord == null)
                    throw new ORecordNotFoundException(record.getIdentity());
                if (ORecordInternal.getRecordType(loadedRecord) == ODocument.RECORD_TYPE && ORecordInternal.getRecordType(loadedRecord) == ORecordInternal.getRecordType(record)) {
                    ((ODocument) loadedRecord).merge((ODocument) record, false, false);
                    loadedRecord.setDirty();
                    ORecordInternal.setContentChanged(loadedRecord, contentChanged);
                    ORecordInternal.setVersion(loadedRecord, record.getVersion());
                    entry.getValue().record = loadedRecord;
                    // SAVE THE RECORD TO RETRIEVE THEM FOR THE NEW VERSIONS TO SEND BACK TO THE REQUESTER
                    updatedRecords.put((ORecordId) entry.getKey(), entry.getValue().getRecord());
                }
            }
            addRecord(entry.getValue().getRecord(), entry.getValue().type, null);
        }
        tempEntries.clear();
        // UNMARSHALL ALL THE RECORD AT THE END TO BE SURE ALL THE RECORD ARE LOADED IN LOCAL TX
        for (ORecord record : createdRecords.values()) {
            unmarshallRecord(record);
            if (record instanceof ODocument) {
                // Force conversion of value to class for trigger default values.
                ODocumentInternal.autoConvertValueToClass(connection.getDatabase(), (ODocument) record);
            }
        }
        for (ORecord record : updatedRecords.values()) unmarshallRecord(record);
    } catch (IOException e) {
        rollback();
        throw OException.wrapException(new OSerializationException("Cannot read transaction record from the network. Transaction aborted"), e);
    }
}
Also used : OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OException(com.orientechnologies.common.exception.OException) IOException(java.io.IOException) IOException(java.io.IOException) ORecordId(com.orientechnologies.orient.core.id.ORecordId) OTransactionAbortedException(com.orientechnologies.orient.core.exception.OTransactionAbortedException) ORecordOperation(com.orientechnologies.orient.core.db.record.ORecordOperation) OTransactionException(com.orientechnologies.orient.core.exception.OTransactionException) ORecord(com.orientechnologies.orient.core.record.ORecord) ORecordNotFoundException(com.orientechnologies.orient.core.exception.ORecordNotFoundException) ORecordSerializer(com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer) ORID(com.orientechnologies.orient.core.id.ORID) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OSerializationException (com.orientechnologies.orient.core.exception.OSerializationException)34 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)11 OException (com.orientechnologies.common.exception.OException)10 IOException (java.io.IOException)9 OType (com.orientechnologies.orient.core.metadata.schema.OType)7 ODatabaseObject (com.orientechnologies.orient.core.db.object.ODatabaseObject)6 ORecord (com.orientechnologies.orient.core.record.ORecord)6 ORID (com.orientechnologies.orient.core.id.ORID)5 ORecordId (com.orientechnologies.orient.core.id.ORecordId)5 OSerializableStream (com.orientechnologies.orient.core.serialization.OSerializableStream)5 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 Map (java.util.Map)4 Entry (java.util.Map.Entry)4 ORecordLazyMap (com.orientechnologies.orient.core.db.record.ORecordLazyMap)3 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)3 OProperty (com.orientechnologies.orient.core.metadata.schema.OProperty)3 ODocumentSerializable (com.orientechnologies.orient.core.serialization.ODocumentSerializable)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ParseException (java.text.ParseException)3