Search in sources :

Example 1 with OSerializableStream

use of com.orientechnologies.orient.core.serialization.OSerializableStream in project orientdb by orientechnologies.

the class ORecordSerializerBinaryV0 method deserializeValue.

@Override
public Object deserializeValue(final BytesContainer bytes, final OType type, final ODocument ownerDocument) {
    Object value = null;
    switch(type) {
        case INTEGER:
            value = OVarIntSerializer.readAsInteger(bytes);
            break;
        case LONG:
            value = OVarIntSerializer.readAsLong(bytes);
            break;
        case SHORT:
            value = OVarIntSerializer.readAsShort(bytes);
            break;
        case STRING:
            value = readString(bytes);
            break;
        case DOUBLE:
            value = Double.longBitsToDouble(readLong(bytes));
            break;
        case FLOAT:
            value = Float.intBitsToFloat(readInteger(bytes));
            break;
        case BYTE:
            value = readByte(bytes);
            break;
        case BOOLEAN:
            value = readByte(bytes) == 1;
            break;
        case DATETIME:
            value = new Date(OVarIntSerializer.readAsLong(bytes));
            break;
        case DATE:
            long savedTime = OVarIntSerializer.readAsLong(bytes) * MILLISEC_PER_DAY;
            savedTime = convertDayToTimezone(TimeZone.getTimeZone("GMT"), ODateHelper.getDatabaseTimeZone(), savedTime);
            value = new Date(savedTime);
            break;
        case EMBEDDED:
            value = new ODocument();
            deserialize((ODocument) value, bytes);
            if (((ODocument) value).containsField(ODocumentSerializable.CLASS_NAME)) {
                String className = ((ODocument) value).field(ODocumentSerializable.CLASS_NAME);
                try {
                    Class<?> clazz = Class.forName(className);
                    ODocumentSerializable newValue = (ODocumentSerializable) clazz.newInstance();
                    newValue.fromDocument((ODocument) value);
                    value = newValue;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else
                ODocumentInternal.addOwner((ODocument) value, ownerDocument);
            break;
        case EMBEDDEDSET:
            value = readEmbeddedSet(bytes, ownerDocument);
            break;
        case EMBEDDEDLIST:
            value = readEmbeddedList(bytes, ownerDocument);
            break;
        case LINKSET:
            value = readLinkCollection(bytes, new ORecordLazySet(ownerDocument));
            break;
        case LINKLIST:
            value = readLinkCollection(bytes, new ORecordLazyList(ownerDocument));
            break;
        case BINARY:
            value = readBinary(bytes);
            break;
        case LINK:
            value = readOptimizedLink(bytes);
            break;
        case LINKMAP:
            value = readLinkMap(bytes, ownerDocument);
            break;
        case EMBEDDEDMAP:
            value = readEmbeddedMap(bytes, ownerDocument);
            break;
        case DECIMAL:
            value = ODecimalSerializer.INSTANCE.deserialize(bytes.bytes, bytes.offset);
            bytes.skip(ODecimalSerializer.INSTANCE.getObjectSize(bytes.bytes, bytes.offset));
            break;
        case LINKBAG:
            ORidBag bag = new ORidBag();
            bag.fromStream(bytes);
            bag.setOwner(ownerDocument);
            value = bag;
            break;
        case TRANSIENT:
            break;
        case CUSTOM:
            try {
                String className = readString(bytes);
                Class<?> clazz = Class.forName(className);
                OSerializableStream stream = (OSerializableStream) clazz.newInstance();
                stream.fromStream(readBinary(bytes));
                if (stream instanceof OSerializableWrapper)
                    value = ((OSerializableWrapper) stream).getSerializable();
                else
                    value = stream;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            break;
        case ANY:
            break;
    }
    return value;
}
Also used : ORidBag(com.orientechnologies.orient.core.db.record.ridbag.ORidBag) OException(com.orientechnologies.common.exception.OException) ORecordNotFoundException(com.orientechnologies.orient.core.exception.ORecordNotFoundException) ODatabaseException(com.orientechnologies.orient.core.exception.ODatabaseException) OValidationException(com.orientechnologies.orient.core.exception.OValidationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OSerializableStream(com.orientechnologies.orient.core.serialization.OSerializableStream) ODocumentSerializable(com.orientechnologies.orient.core.serialization.ODocumentSerializable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 2 with OSerializableStream

use of com.orientechnologies.orient.core.serialization.OSerializableStream in project orientdb by orientechnologies.

the class ORecordSerializerNetworkV0 method serializeValue.

@SuppressWarnings("unchecked")
public int serializeValue(final BytesContainer bytes, Object value, final OType type, final OType linkedType) {
    int pointer = 0;
    switch(type) {
        case INTEGER:
        case LONG:
        case SHORT:
            pointer = OVarIntSerializer.write(bytes, ((Number) value).longValue());
            break;
        case STRING:
            pointer = writeString(bytes, value.toString());
            break;
        case DOUBLE:
            long dg = Double.doubleToLongBits((Double) value);
            pointer = bytes.alloc(OLongSerializer.LONG_SIZE);
            OLongSerializer.INSTANCE.serializeLiteral(dg, bytes.bytes, pointer);
            break;
        case FLOAT:
            int fg = Float.floatToIntBits((Float) value);
            pointer = bytes.alloc(OIntegerSerializer.INT_SIZE);
            OIntegerSerializer.INSTANCE.serializeLiteral(fg, bytes.bytes, pointer);
            break;
        case BYTE:
            pointer = bytes.alloc(1);
            bytes.bytes[pointer] = (Byte) value;
            break;
        case BOOLEAN:
            pointer = bytes.alloc(1);
            bytes.bytes[pointer] = ((Boolean) value) ? (byte) 1 : (byte) 0;
            break;
        case DATETIME:
            if (value instanceof Long) {
                pointer = OVarIntSerializer.write(bytes, (Long) value);
            } else
                pointer = OVarIntSerializer.write(bytes, ((Date) value).getTime());
            break;
        case DATE:
            long dateValue;
            if (value instanceof Long) {
                dateValue = (Long) value;
            } else
                dateValue = ((Date) value).getTime();
            dateValue = convertDayToTimezone(ODateHelper.getDatabaseTimeZone(), TimeZone.getTimeZone("GMT"), dateValue);
            pointer = OVarIntSerializer.write(bytes, dateValue / MILLISEC_PER_DAY);
            break;
        case EMBEDDED:
            pointer = bytes.offset;
            if (value instanceof ODocumentSerializable) {
                ODocument cur = ((ODocumentSerializable) value).toDocument();
                cur.field(ODocumentSerializable.CLASS_NAME, value.getClass().getName());
                serialize(cur, bytes, false);
            } else {
                serialize((ODocument) value, bytes, false);
            }
            break;
        case EMBEDDEDSET:
        case EMBEDDEDLIST:
            if (value.getClass().isArray())
                pointer = writeEmbeddedCollection(bytes, Arrays.asList(OMultiValue.array(value)), linkedType);
            else
                pointer = writeEmbeddedCollection(bytes, (Collection<?>) value, linkedType);
            break;
        case DECIMAL:
            BigDecimal decimalValue = (BigDecimal) value;
            pointer = bytes.alloc(ODecimalSerializer.INSTANCE.getObjectSize(decimalValue));
            ODecimalSerializer.INSTANCE.serialize(decimalValue, bytes.bytes, pointer);
            break;
        case BINARY:
            pointer = writeBinary(bytes, (byte[]) (value));
            break;
        case LINKSET:
        case LINKLIST:
            Collection<OIdentifiable> ridCollection = (Collection<OIdentifiable>) value;
            pointer = writeLinkCollection(bytes, ridCollection);
            break;
        case LINK:
            if (!(value instanceof OIdentifiable))
                throw new OValidationException("Value '" + value + "' is not a OIdentifiable");
            pointer = writeOptimizedLink(bytes, (OIdentifiable) value);
            break;
        case LINKMAP:
            pointer = writeLinkMap(bytes, (Map<Object, OIdentifiable>) value);
            break;
        case EMBEDDEDMAP:
            pointer = writeEmbeddedMap(bytes, (Map<Object, Object>) value);
            break;
        case LINKBAG:
            pointer = ((ORidBag) value).toStream(bytes);
            break;
        case CUSTOM:
            if (!(value instanceof OSerializableStream))
                value = new OSerializableWrapper((Serializable) value);
            pointer = writeString(bytes, value.getClass().getName());
            writeBinary(bytes, ((OSerializableStream) value).toStream());
            break;
        case TRANSIENT:
            break;
        case ANY:
            break;
    }
    return pointer;
}
Also used : OValidationException(com.orientechnologies.orient.core.exception.OValidationException) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) BigDecimal(java.math.BigDecimal) OSerializableStream(com.orientechnologies.orient.core.serialization.OSerializableStream) ODocumentSerializable(com.orientechnologies.orient.core.serialization.ODocumentSerializable) OTrackedMap(com.orientechnologies.orient.core.db.record.OTrackedMap) ORecordLazyMap(com.orientechnologies.orient.core.db.record.ORecordLazyMap) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 3 with OSerializableStream

use of com.orientechnologies.orient.core.serialization.OSerializableStream in project orientdb by orientechnologies.

the class ORecordSerializerNetworkV0 method deserializeValue.

public Object deserializeValue(BytesContainer bytes, OType type, ODocument document) {
    Object value = null;
    switch(type) {
        case INTEGER:
            value = OVarIntSerializer.readAsInteger(bytes);
            break;
        case LONG:
            value = OVarIntSerializer.readAsLong(bytes);
            break;
        case SHORT:
            value = OVarIntSerializer.readAsShort(bytes);
            break;
        case STRING:
            value = readString(bytes);
            break;
        case DOUBLE:
            value = Double.longBitsToDouble(readLong(bytes));
            break;
        case FLOAT:
            value = Float.intBitsToFloat(readInteger(bytes));
            break;
        case BYTE:
            value = readByte(bytes);
            break;
        case BOOLEAN:
            value = readByte(bytes) == 1;
            break;
        case DATETIME:
            value = new Date(OVarIntSerializer.readAsLong(bytes));
            break;
        case DATE:
            long savedTime = OVarIntSerializer.readAsLong(bytes) * MILLISEC_PER_DAY;
            savedTime = convertDayToTimezone(TimeZone.getTimeZone("GMT"), ODateHelper.getDatabaseTimeZone(), savedTime);
            value = new Date(savedTime);
            break;
        case EMBEDDED:
            value = new ODocument();
            deserialize((ODocument) value, bytes);
            if (((ODocument) value).containsField(ODocumentSerializable.CLASS_NAME)) {
                String className = ((ODocument) value).field(ODocumentSerializable.CLASS_NAME);
                try {
                    Class<?> clazz = Class.forName(className);
                    ODocumentSerializable newValue = (ODocumentSerializable) clazz.newInstance();
                    newValue.fromDocument((ODocument) value);
                    value = newValue;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else
                ODocumentInternal.addOwner((ODocument) value, document);
            break;
        case EMBEDDEDSET:
            value = readEmbeddedCollection(bytes, new OTrackedSet<Object>(document), document);
            break;
        case EMBEDDEDLIST:
            value = readEmbeddedCollection(bytes, new OTrackedList<Object>(document), document);
            break;
        case LINKSET:
            value = readLinkCollection(bytes, new ORecordLazySet(document));
            break;
        case LINKLIST:
            value = readLinkCollection(bytes, new ORecordLazyList(document));
            break;
        case BINARY:
            value = readBinary(bytes);
            break;
        case LINK:
            value = readOptimizedLink(bytes);
            break;
        case LINKMAP:
            value = readLinkMap(bytes, document);
            break;
        case EMBEDDEDMAP:
            value = readEmbeddedMap(bytes, document);
            break;
        case DECIMAL:
            value = ODecimalSerializer.INSTANCE.deserialize(bytes.bytes, bytes.offset);
            bytes.skip(ODecimalSerializer.INSTANCE.getObjectSize(bytes.bytes, bytes.offset));
            break;
        case LINKBAG:
            ORidBag bag = new ORidBag();
            bag.fromStream(bytes);
            bag.setOwner(document);
            value = bag;
            break;
        case TRANSIENT:
            break;
        case CUSTOM:
            try {
                String className = readString(bytes);
                Class<?> clazz = Class.forName(className);
                OSerializableStream stream = (OSerializableStream) clazz.newInstance();
                stream.fromStream(readBinary(bytes));
                if (stream instanceof OSerializableWrapper)
                    value = ((OSerializableWrapper) stream).getSerializable();
                else
                    value = stream;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            break;
        case ANY:
            break;
    }
    return value;
}
Also used : ORecordLazyList(com.orientechnologies.orient.core.db.record.ORecordLazyList) ORidBag(com.orientechnologies.orient.core.db.record.ridbag.ORidBag) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) OException(com.orientechnologies.common.exception.OException) OStorageException(com.orientechnologies.orient.core.exception.OStorageException) OValidationException(com.orientechnologies.orient.core.exception.OValidationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OTrackedSet(com.orientechnologies.orient.core.db.record.OTrackedSet) OTrackedList(com.orientechnologies.orient.core.db.record.OTrackedList) OSerializableStream(com.orientechnologies.orient.core.serialization.OSerializableStream) ODocumentSerializable(com.orientechnologies.orient.core.serialization.ODocumentSerializable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 4 with OSerializableStream

use of com.orientechnologies.orient.core.serialization.OSerializableStream in project orientdb by orientechnologies.

the class OStorageRemote method command.

/**
   * Execute the command remotely and get the results back.
   */
public Object command(final OCommandRequestText iCommand) {
    if (!(iCommand instanceof OSerializableStream))
        throw new OCommandExecutionException("Cannot serialize the command to be executed to the server side.");
    final boolean live = iCommand instanceof OLiveQuery;
    final ODatabaseDocument database = ODatabaseRecordThreadLocal.INSTANCE.get();
    return networkOperation(new OStorageRemoteOperation<Object>() {

        @Override
        public Object execute(final OChannelBinaryAsynchClient network, OStorageRemoteSession session) throws IOException {
            Object result = null;
            session.commandExecuting = true;
            try {
                final boolean asynch = iCommand instanceof OCommandRequestAsynch && ((OCommandRequestAsynch) iCommand).isAsynchronous();
                try {
                    beginRequest(network, OChannelBinaryProtocol.REQUEST_COMMAND, session);
                    if (live) {
                        network.writeByte((byte) 'l');
                    } else {
                        // ASYNC / SYNC
                        network.writeByte((byte) (asynch ? 'a' : 's'));
                    }
                    network.writeBytes(OStreamSerializerAnyStreamable.INSTANCE.toStream(iCommand));
                } finally {
                    endRequest(network);
                }
                try {
                    beginResponse(network, session);
                    // Collection of prefetched temporary record (nested projection record), to refer for avoid garbage collection.
                    List<ORecord> temporaryResults = new ArrayList<ORecord>();
                    boolean addNextRecord = true;
                    if (asynch) {
                        byte status;
                        // ASYNCH: READ ONE RECORD AT TIME
                        while ((status = network.readByte()) > 0) {
                            final ORecord record = (ORecord) OChannelBinaryProtocol.readIdentifiable(network);
                            if (record == null)
                                continue;
                            switch(status) {
                                case 1:
                                    // PUT AS PART OF THE RESULT SET. INVOKE THE LISTENER
                                    if (addNextRecord) {
                                        addNextRecord = iCommand.getResultListener().result(record);
                                        database.getLocalCache().updateRecord(record);
                                    }
                                    break;
                                case 2:
                                    if (record.getIdentity().getClusterId() == -2)
                                        temporaryResults.add(record);
                                    // PUT IN THE CLIENT LOCAL CACHE
                                    database.getLocalCache().updateRecord(record);
                            }
                        }
                    } else {
                        result = readSynchResult(network, database, temporaryResults);
                        if (live) {
                            final ODocument doc = ((List<ODocument>) result).get(0);
                            final Integer token = doc.field("token");
                            final Boolean unsubscribe = doc.field("unsubscribe");
                            if (token != null) {
                                if (Boolean.TRUE.equals(unsubscribe)) {
                                    if (OStorageRemote.this.asynchEventListener != null)
                                        OStorageRemote.this.asynchEventListener.unregisterLiveListener(token);
                                } else {
                                    final OLiveResultListener listener = (OLiveResultListener) iCommand.getResultListener();
                                    ODatabaseDocumentInternal current = ODatabaseRecordThreadLocal.INSTANCE.get();
                                    final ODatabaseDocument dbCopy = current.copy();
                                    ORemoteConnectionPool pool = OStorageRemote.this.connectionManager.getPool(network.getServerURL());
                                    OStorageRemote.this.asynchEventListener.registerLiveListener(pool, token, new OLiveResultListener() {

                                        @Override
                                        public void onUnsubscribe(int iLiveToken) {
                                            listener.onUnsubscribe(iLiveToken);
                                            dbCopy.close();
                                        }

                                        @Override
                                        public void onLiveResult(int iLiveToken, ORecordOperation iOp) throws OException {
                                            dbCopy.activateOnCurrentThread();
                                            listener.onLiveResult(iLiveToken, iOp);
                                        }

                                        @Override
                                        public void onError(int iLiveToken) {
                                            listener.onError(iLiveToken);
                                            dbCopy.close();
                                        }
                                    });
                                }
                            } else {
                                throw new OStorageException("Cannot execute live query, returned null token");
                            }
                        }
                    }
                    if (!temporaryResults.isEmpty()) {
                        if (result instanceof OBasicResultSet<?>) {
                            ((OBasicResultSet<?>) result).setTemporaryRecordCache(temporaryResults);
                        }
                    }
                    return result;
                } finally {
                    endResponse(network);
                }
            } finally {
                session.commandExecuting = false;
                if (iCommand.getResultListener() != null && !live)
                    iCommand.getResultListener().end();
            }
        }
    }, "Error on executing command: " + iCommand);
}
Also used : OIOException(com.orientechnologies.common.io.OIOException) IOException(java.io.IOException) OChannelBinaryAsynchClient(com.orientechnologies.orient.client.binary.OChannelBinaryAsynchClient) OCommandRequestAsynch(com.orientechnologies.orient.core.command.OCommandRequestAsynch) OLiveResultListener(com.orientechnologies.orient.core.sql.query.OLiveResultListener) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ORecordOperation(com.orientechnologies.orient.core.db.record.ORecordOperation) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OLiveQuery(com.orientechnologies.orient.core.sql.query.OLiveQuery) ORecord(com.orientechnologies.orient.core.record.ORecord) OSerializableStream(com.orientechnologies.orient.core.serialization.OSerializableStream) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 5 with OSerializableStream

use of com.orientechnologies.orient.core.serialization.OSerializableStream in project orientdb by orientechnologies.

the class OStreamSerializerAnyStreamable method toStream.

/**
   * Serialize the class name size + class name + object content
   */
public byte[] toStream(final Object iObject) throws IOException {
    if (iObject == null)
        return null;
    if (!(iObject instanceof OSerializableStream))
        throw new OSerializationException("Cannot serialize the object [" + iObject.getClass() + ":" + iObject + "] since it does not implement the OSerializableStream interface");
    OSerializableStream stream = (OSerializableStream) iObject;
    // SERIALIZE THE CLASS NAME
    final byte[] className;
    if (iObject instanceof OLiveQuery<?>)
        className = iObject.getClass().getName().getBytes("UTF-8");
    else if (iObject instanceof OSQLSynchQuery<?>)
        className = QUERY_COMMAND_CLASS_ASBYTES;
    else if (iObject instanceof OCommandSQL)
        className = SQL_COMMAND_CLASS_ASBYTES;
    else if (iObject instanceof OCommandScript)
        className = SCRIPT_COMMAND_CLASS_ASBYTES;
    else {
        if (iObject == null)
            className = null;
        else
            className = iObject.getClass().getName().getBytes("UTF-8");
    }
    // SERIALIZE THE OBJECT CONTENT
    byte[] objectContent = stream.toStream();
    byte[] result = new byte[4 + className.length + objectContent.length];
    // COPY THE CLASS NAME SIZE + CLASS NAME + OBJECT CONTENT
    System.arraycopy(OBinaryProtocol.int2bytes(className.length), 0, result, 0, 4);
    System.arraycopy(className, 0, result, 4, className.length);
    System.arraycopy(objectContent, 0, result, 4 + className.length, objectContent.length);
    return result;
}
Also used : OCommandSQL(com.orientechnologies.orient.core.sql.OCommandSQL) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OLiveQuery(com.orientechnologies.orient.core.sql.query.OLiveQuery) OCommandScript(com.orientechnologies.orient.core.command.script.OCommandScript) OSerializableStream(com.orientechnologies.orient.core.serialization.OSerializableStream)

Aggregations

OSerializableStream (com.orientechnologies.orient.core.serialization.OSerializableStream)11 OSerializationException (com.orientechnologies.orient.core.exception.OSerializationException)7 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)7 ODocumentSerializable (com.orientechnologies.orient.core.serialization.ODocumentSerializable)5 OException (com.orientechnologies.common.exception.OException)4 OValidationException (com.orientechnologies.orient.core.exception.OValidationException)4 IOException (java.io.IOException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 OCommandScript (com.orientechnologies.orient.core.command.script.OCommandScript)2 ORidBag (com.orientechnologies.orient.core.db.record.ridbag.ORidBag)2 ORecord (com.orientechnologies.orient.core.record.ORecord)2 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)2 OLiveQuery (com.orientechnologies.orient.core.sql.query.OLiveQuery)2 BigDecimal (java.math.BigDecimal)2 OIOException (com.orientechnologies.common.io.OIOException)1 OChannelBinaryAsynchClient (com.orientechnologies.orient.client.binary.OChannelBinaryAsynchClient)1 OCommandRequestAsynch (com.orientechnologies.orient.core.command.OCommandRequestAsynch)1 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)1 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)1 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)1