Search in sources :

Example 21 with OSerializationException

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

the class OSerializableWrapper method fromStream.

@Override
public OSerializableStream fromStream(byte[] iStream) throws OSerializationException {
    ByteArrayInputStream stream = new ByteArrayInputStream(iStream);
    try {
        ObjectInputStream reader = new ObjectInputStream(stream);
        serializable = (Serializable) reader.readObject();
        reader.close();
    } catch (Exception e) {
        throw OException.wrapException(new ODatabaseException("Error on deserialization of Serializable"), e);
    }
    return this;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ODatabaseException(com.orientechnologies.orient.core.exception.ODatabaseException) ODatabaseException(com.orientechnologies.orient.core.exception.ODatabaseException) IOException(java.io.IOException) OException(com.orientechnologies.common.exception.OException) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) ObjectInputStream(java.io.ObjectInputStream)

Example 22 with OSerializationException

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

the class ORecordSerializerCSVAbstract method fieldToStream.

public void fieldToStream(final ODocument iRecord, final StringBuilder iOutput, OUserObject2RecordHandler iObjHandler, final OType iType, final OClass iLinkedClass, final OType iLinkedType, final String iName, final Object iValue, final boolean iSaveOnlyDirty) {
    if (iValue == null)
        return;
    final long timer = PROFILER.startChrono();
    switch(iType) {
        case LINK:
            {
                if (!(iValue instanceof OIdentifiable))
                    throw new OSerializationException("Found an unexpected type during marshalling of a LINK where a OIdentifiable (ORID or any Record) was expected. The string representation of the object is: " + iValue);
                if (!((OIdentifiable) iValue).getIdentity().isValid() && iValue instanceof ODocument && ((ODocument) iValue).isEmbedded()) {
                    // WRONG: IT'S EMBEDDED!
                    fieldToStream(iRecord, iOutput, iObjHandler, OType.EMBEDDED, iLinkedClass, iLinkedType, iName, iValue, iSaveOnlyDirty);
                } else {
                    final Object link = linkToStream(iOutput, iRecord, iValue);
                    if (link != null)
                        // OVERWRITE CONTENT
                        iRecord.field(iName, link);
                    PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), "Serialize link to string", timer);
                }
                break;
            }
        case LINKLIST:
            {
                iOutput.append(OStringSerializerHelper.LIST_BEGIN);
                if (iValue instanceof ORecordLazyList && ((ORecordLazyList) iValue).getStreamedContent() != null) {
                    iOutput.append(((ORecordLazyList) iValue).getStreamedContent());
                    PROFILER.updateCounter(PROFILER.getProcessMetric("serializer.record.string.linkList2string.cached"), "Serialize linklist to string in stream mode", +1);
                } else {
                    final ORecordLazyList coll;
                    final Iterator<OIdentifiable> it;
                    if (iValue instanceof OMultiCollectionIterator<?>) {
                        final OMultiCollectionIterator<OIdentifiable> iterator = (OMultiCollectionIterator<OIdentifiable>) iValue;
                        iterator.reset();
                        it = iterator;
                        coll = null;
                    } else if (!(iValue instanceof ORecordLazyList)) {
                        // FIRST TIME: CONVERT THE ENTIRE COLLECTION
                        coll = new ORecordLazyList(iRecord);
                        if (iValue.getClass().isArray()) {
                            Iterable<Object> iterab = OMultiValue.getMultiValueIterable(iValue, false);
                            for (Object i : iterab) {
                                coll.add((OIdentifiable) i);
                            }
                        } else {
                            coll.addAll((Collection<? extends OIdentifiable>) iValue);
                            ((Collection<? extends OIdentifiable>) iValue).clear();
                        }
                        iRecord.field(iName, coll);
                        it = coll.rawIterator();
                    } else {
                        // LAZY LIST
                        coll = (ORecordLazyList) iValue;
                        if (coll.getStreamedContent() != null) {
                            // APPEND STREAMED CONTENT
                            iOutput.append(coll.getStreamedContent());
                            PROFILER.updateCounter(PROFILER.getProcessMetric("serializer.record.string.linkList2string.cached"), "Serialize linklist to string in stream mode", +1);
                            it = coll.newItemsIterator();
                        } else
                            it = coll.rawIterator();
                    }
                    if (it != null && it.hasNext()) {
                        final StringBuilder buffer = new StringBuilder(128);
                        for (int items = 0; it.hasNext(); items++) {
                            if (items > 0)
                                buffer.append(OStringSerializerHelper.RECORD_SEPARATOR);
                            final OIdentifiable item = it.next();
                            final OIdentifiable newRid = linkToStream(buffer, iRecord, item);
                            if (newRid != null)
                                ((OLazyIterator<OIdentifiable>) it).update(newRid);
                        }
                        if (coll != null)
                            coll.convertRecords2Links();
                        iOutput.append(buffer);
                        // UPDATE THE STREAM
                        if (coll != null)
                            coll.setStreamedContent(buffer);
                    }
                }
                iOutput.append(OStringSerializerHelper.LIST_END);
                PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkList2string"), "Serialize linklist to string", timer);
                break;
            }
        case LINKSET:
            {
                if (!(iValue instanceof OStringBuilderSerializable)) {
                    if (iValue instanceof OAutoConvertToRecord)
                        ((OAutoConvertToRecord) iValue).setAutoConvertToRecord(false);
                    final Collection<OIdentifiable> coll;
                    // FIRST TIME: CONVERT THE ENTIRE COLLECTION
                    if (!(iValue instanceof ORecordLazySet)) {
                        final ORecordLazySet set = new ORecordLazySet(iRecord);
                        set.addAll((Collection<OIdentifiable>) iValue);
                        iRecord.field(iName, set);
                        coll = set;
                    } else
                        coll = (Collection<OIdentifiable>) iValue;
                    serializeSet(coll, iOutput);
                } else {
                    // LAZY SET
                    final OStringBuilderSerializable coll = (OStringBuilderSerializable) iValue;
                    coll.toStream(iOutput);
                }
                PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkSet2string"), "Serialize linkset to string", timer);
                break;
            }
        case LINKMAP:
            {
                iOutput.append(OStringSerializerHelper.MAP_BEGIN);
                Map<Object, Object> map = (Map<Object, Object>) iValue;
                // LINKED MAP
                if (map instanceof OLazyObjectMapInterface<?>)
                    ((OLazyObjectMapInterface<?>) map).setConvertToRecord(false);
                boolean invalidMap = false;
                try {
                    int items = 0;
                    for (Map.Entry<Object, Object> entry : map.entrySet()) {
                        if (items++ > 0)
                            iOutput.append(OStringSerializerHelper.RECORD_SEPARATOR);
                        fieldTypeToString(iOutput, OType.STRING, entry.getKey());
                        iOutput.append(OStringSerializerHelper.ENTRY_SEPARATOR);
                        final Object link = linkToStream(iOutput, iRecord, entry.getValue());
                        if (link != null && !invalidMap)
                            // IDENTITY IS CHANGED, RE-SET INTO THE COLLECTION TO RECOMPUTE THE HASH
                            invalidMap = true;
                    }
                } finally {
                    if (map instanceof OLazyObjectMapInterface<?>) {
                        ((OLazyObjectMapInterface<?>) map).setConvertToRecord(true);
                    }
                }
                if (invalidMap) {
                    final ORecordLazyMap newMap = new ORecordLazyMap(iRecord, ODocument.RECORD_TYPE);
                    // REPLACE ALL CHANGED ITEMS
                    for (Map.Entry<Object, Object> entry : map.entrySet()) {
                        newMap.put(entry.getKey(), (OIdentifiable) entry.getValue());
                    }
                    map.clear();
                    iRecord.field(iName, newMap);
                }
                iOutput.append(OStringSerializerHelper.MAP_END);
                PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.linkMap2string"), "Serialize linkmap to string", timer);
                break;
            }
        case EMBEDDED:
            if (iValue instanceof ORecord) {
                iOutput.append(OStringSerializerHelper.EMBEDDED_BEGIN);
                toString((ORecord) iValue, iOutput, null, iObjHandler, false, true);
                iOutput.append(OStringSerializerHelper.EMBEDDED_END);
            } else if (iValue instanceof ODocumentSerializable) {
                final ODocument doc = ((ODocumentSerializable) iValue).toDocument();
                doc.field(ODocumentSerializable.CLASS_NAME, iValue.getClass().getName());
                iOutput.append(OStringSerializerHelper.EMBEDDED_BEGIN);
                toString(doc, iOutput, null, iObjHandler, false, true);
                iOutput.append(OStringSerializerHelper.EMBEDDED_END);
            } else if (iValue != null)
                iOutput.append(iValue.toString());
            PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), "Serialize embedded to string", timer);
            break;
        case EMBEDDEDLIST:
            embeddedCollectionToStream(null, iObjHandler, iOutput, iLinkedClass, iLinkedType, iValue, iSaveOnlyDirty, false);
            PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"), "Serialize embeddedlist to string", timer);
            break;
        case EMBEDDEDSET:
            embeddedCollectionToStream(null, iObjHandler, iOutput, iLinkedClass, iLinkedType, iValue, iSaveOnlyDirty, true);
            PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), "Serialize embeddedset to string", timer);
            break;
        case EMBEDDEDMAP:
            {
                embeddedMapToStream(null, iObjHandler, iOutput, iLinkedClass, iLinkedType, iValue, iSaveOnlyDirty);
                PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), "Serialize embeddedmap to string", timer);
                break;
            }
        case LINKBAG:
            {
                iOutput.append(OStringSerializerHelper.BAG_BEGIN);
                ((ORidBag) iValue).toStream(iOutput);
                iOutput.append(OStringSerializerHelper.BAG_END);
                break;
            }
        default:
            fieldTypeToString(iOutput, iType, iValue);
    }
}
Also used : ORecordLazyList(com.orientechnologies.orient.core.db.record.ORecordLazyList) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) OStringBuilderSerializable(com.orientechnologies.orient.core.serialization.serializer.string.OStringBuilderSerializable) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ORecordLazyMap(com.orientechnologies.orient.core.db.record.ORecordLazyMap) OAutoConvertToRecord(com.orientechnologies.orient.core.db.record.OAutoConvertToRecord) Entry(java.util.Map.Entry) OLazyIterator(com.orientechnologies.common.collection.OLazyIterator) OMultiCollectionIterator(com.orientechnologies.common.collection.OMultiCollectionIterator) ORecord(com.orientechnologies.orient.core.record.ORecord) OMultiCollectionIterator(com.orientechnologies.common.collection.OMultiCollectionIterator) OLazyIterator(com.orientechnologies.common.collection.OLazyIterator) Iterator(java.util.Iterator) Collection(java.util.Collection) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) OLazyObjectMapInterface(com.orientechnologies.orient.core.db.object.OLazyObjectMapInterface) ODocumentSerializable(com.orientechnologies.orient.core.serialization.ODocumentSerializable) 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 23 with OSerializationException

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

the class ORecordSerializerJSON method fromString.

public ORecord fromString(String iSource, ORecord iRecord, final String[] iFields, final String iOptions, boolean needReload) {
    iSource = unwrapSource(iSource);
    boolean noMap = false;
    if (iOptions != null) {
        final String[] format = iOptions.split(",");
        for (String f : format) if (f.equalsIgnoreCase("noMap"))
            noMap = true;
    }
    if (iRecord != null)
        // RESET ALL THE FIELDS
        iRecord.clear();
    final List<String> fields = OStringSerializerHelper.smartSplit(iSource, PARAMETER_SEPARATOR, 0, -1, true, true, false, false, ' ', '\n', '\r', '\t');
    if (fields.size() % 2 != 0)
        throw new OSerializationException("Error on unmarshalling JSON content: wrong format \"" + iSource + "\". Use <field> : <value>");
    Map<String, Character> fieldTypes = null;
    if (fields != null && fields.size() > 0) {
        // SEARCH FOR FIELD TYPES IF ANY
        for (int i = 0; i < fields.size(); i += 2) {
            final String fieldName = OIOUtils.getStringContent(fields.get(i));
            final String fieldValue = fields.get(i + 1);
            final String fieldValueAsString = OIOUtils.getStringContent(fieldValue);
            if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) {
                fieldTypes = loadFieldTypes(fieldTypes, fieldValueAsString);
            } else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
                if (iRecord == null || ORecordInternal.getRecordType(iRecord) != fieldValueAsString.charAt(0)) {
                    // CREATE THE RIGHT RECORD INSTANCE
                    iRecord = Orient.instance().getRecordFactoryManager().newInstance((byte) fieldValueAsString.charAt(0));
                }
            } else if (needReload && fieldName.equals(ODocumentHelper.ATTRIBUTE_RID) && iRecord instanceof ODocument) {
                if (fieldValue != null && fieldValue.length() > 0) {
                    ORecord localRecord = ODatabaseRecordThreadLocal.INSTANCE.get().load(new ORecordId(fieldValueAsString));
                    if (localRecord != null)
                        iRecord = localRecord;
                }
            } else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_CLASS) && iRecord instanceof ODocument) {
                ODocumentInternal.fillClassNameIfNeeded(((ODocument) iRecord), "null".equals(fieldValueAsString) ? null : fieldValueAsString);
            }
        }
        if (iRecord == null)
            iRecord = new ODocument();
        try {
            for (int i = 0; i < fields.size(); i += 2) {
                final String fieldName = OIOUtils.getStringContent(fields.get(i));
                final String fieldValue = fields.get(i + 1);
                final String fieldValueAsString = OIOUtils.getStringContent(fieldValue);
                // RECORD ATTRIBUTES
                if (fieldName.equals(ODocumentHelper.ATTRIBUTE_RID))
                    ORecordInternal.setIdentity(iRecord, new ORecordId(fieldValueAsString));
                else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION))
                    ORecordInternal.setVersion(iRecord, Integer.parseInt(fieldValue));
                else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
                    continue;
                } else if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) {
                    continue;
                } else if (fieldName.equals("value") && !(iRecord instanceof ODocument)) {
                    // RECORD VALUE(S)
                    if ("null".equals(fieldValue))
                        iRecord.fromStream(OCommonConst.EMPTY_BYTE_ARRAY);
                    else if (iRecord instanceof OBlob) {
                        // BYTES
                        iRecord.fromStream(OBase64Utils.decode(fieldValueAsString));
                    } else if (iRecord instanceof ORecordStringable) {
                        ((ORecordStringable) iRecord).value(fieldValueAsString);
                    } else
                        throw new IllegalArgumentException("unsupported type of record");
                } else if (iRecord instanceof ODocument) {
                    final ODocument doc = ((ODocument) iRecord);
                    // DETERMINE THE TYPE FROM THE SCHEMA
                    OType type = determineType(doc, fieldName);
                    final Object v = getValue(doc, fieldName, fieldValue, fieldValueAsString, type, null, fieldTypes, noMap, iOptions);
                    if (v != null)
                        if (v instanceof Collection<?> && !((Collection<?>) v).isEmpty()) {
                            if (v instanceof ORecordLazyMultiValue)
                                ((ORecordLazyMultiValue) v).setAutoConvertToRecord(false);
                            // CHECK IF THE COLLECTION IS EMBEDDED
                            if (type == null) {
                                // TRY TO UNDERSTAND BY FIRST ITEM
                                Object first = ((Collection<?>) v).iterator().next();
                                if (first != null && first instanceof ORecord && !((ORecord) first).getIdentity().isValid())
                                    type = v instanceof Set<?> ? OType.EMBEDDEDSET : OType.EMBEDDEDLIST;
                            }
                            if (type != null) {
                                // TREAT IT AS EMBEDDED
                                doc.field(fieldName, v, type);
                                continue;
                            }
                        } else if (v instanceof Map<?, ?> && !((Map<?, ?>) v).isEmpty()) {
                            // CHECK IF THE MAP IS EMBEDDED
                            Object first = ((Map<?, ?>) v).values().iterator().next();
                            if (first != null && first instanceof ORecord && !((ORecord) first).getIdentity().isValid()) {
                                doc.field(fieldName, v, OType.EMBEDDEDMAP);
                                continue;
                            }
                        } else if (v instanceof ODocument && type != null && type.isLink()) {
                            String className = ((ODocument) v).getClassName();
                            if (className != null && className.length() > 0)
                                ((ODocument) v).save();
                        }
                    if (type == null && fieldTypes != null && fieldTypes.containsKey(fieldName))
                        type = ORecordSerializerStringAbstract.getType(fieldValue, fieldTypes.get(fieldName));
                    if (v instanceof OTrackedSet<?>) {
                        if (OMultiValue.getFirstValue((Set<?>) v) instanceof OIdentifiable)
                            type = OType.LINKSET;
                    } else if (v instanceof OTrackedList<?>) {
                        if (OMultiValue.getFirstValue((List<?>) v) instanceof OIdentifiable)
                            type = OType.LINKLIST;
                    }
                    if (type != null)
                        doc.field(fieldName, v, type);
                    else
                        doc.field(fieldName, v);
                }
            }
        } catch (Exception e) {
            if (iRecord.getIdentity().isValid())
                throw OException.wrapException(new OSerializationException("Error on unmarshalling JSON content for record " + iRecord.getIdentity()), e);
            else
                throw OException.wrapException(new OSerializationException("Error on unmarshalling JSON content for record: " + iSource), e);
        }
    }
    return iRecord;
}
Also used : OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OTrackedList(com.orientechnologies.orient.core.db.record.OTrackedList) ORecordLazyList(com.orientechnologies.orient.core.db.record.ORecordLazyList) List(java.util.List) OTrackedList(com.orientechnologies.orient.core.db.record.OTrackedList) ORecordStringable(com.orientechnologies.orient.core.record.ORecordStringable) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OType(com.orientechnologies.orient.core.metadata.schema.OType) ORecordId(com.orientechnologies.orient.core.id.ORecordId) OException(com.orientechnologies.common.exception.OException) ParseException(java.text.ParseException) IOException(java.io.IOException) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) ORecordLazyMultiValue(com.orientechnologies.orient.core.db.record.ORecordLazyMultiValue) ORecord(com.orientechnologies.orient.core.record.ORecord) Collection(java.util.Collection) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 24 with OSerializationException

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

the class ORecordSerializerJSON method getValue.

@SuppressWarnings("unchecked")
private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType iType, OType iLinkedType, final Map<String, Character> iFieldTypes, final boolean iNoMap, final String iOptions) {
    if (iFieldValue.equals("null"))
        return null;
    if (iFieldName != null && ODocumentInternal.getImmutableSchemaClass(iRecord) != null) {
        final OProperty p = ODocumentInternal.getImmutableSchemaClass(iRecord).getProperty(iFieldName);
        if (p != null) {
            iType = p.getType();
            iLinkedType = p.getLinkedType();
        }
    }
    if (iType == null && iFieldTypes != null && iFieldTypes.containsKey(iFieldName))
        iType = ORecordSerializerStringAbstract.getType(iFieldValue, iFieldTypes.get(iFieldName));
    if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) {
        return getValueAsObjectOrMap(iRecord, iFieldValue, iType, iLinkedType, iFieldTypes, iNoMap, iOptions);
    } else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) {
        return getValueAsCollection(iRecord, iFieldValue, iType, iLinkedType, iFieldTypes, iNoMap, iOptions);
    }
    if (iType == null || iType == OType.ANY)
        // TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE
        if (iFieldValue.charAt(0) != '\"' && iFieldValue.charAt(0) != '\'') {
            if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true"))
                iType = OType.BOOLEAN;
            else {
                Character c = null;
                if (iFieldTypes != null) {
                    c = iFieldTypes.get(iFieldName);
                    if (c != null)
                        iType = ORecordSerializerStringAbstract.getType(iFieldValue + c);
                }
                if (c == null && !iFieldValue.isEmpty()) {
                    // TRY TO AUTODETERMINE THE BEST TYPE
                    if (ORecordId.isA(iFieldValue))
                        iType = OType.LINK;
                    else if (iFieldValue.matches(".*[\\.Ee].*")) {
                        // DECIMAL FORMAT: DETERMINE IF DOUBLE OR FLOAT
                        final Double v = new Double(OIOUtils.getStringContent(iFieldValue));
                        return v;
                    // REMOVED TRUNK to float
                    // if (canBeTrunkedToFloat(v))
                    // return v.floatValue();
                    // else
                    // return v;
                    } else {
                        final Long v = new Long(OIOUtils.getStringContent(iFieldValue));
                        if (canBeTrunkedToInt(v))
                            return v.intValue();
                        else
                            return v;
                    }
                }
            }
        } else if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}"))
            iType = OType.EMBEDDED;
        else {
            if (ORecordId.isA(iFieldValueAsString))
                iType = OType.LINK;
            if (iFieldTypes != null) {
                Character c = iFieldTypes.get(iFieldName);
                if (c != null)
                    iType = ORecordSerializerStringAbstract.getType(iFieldValueAsString, c);
            }
            if (iType == null)
                iType = OType.STRING;
        }
    if (iType != null)
        switch(iType) {
            case STRING:
                return decodeJSON(iFieldValueAsString);
            case LINK:
                final int pos = iFieldValueAsString.indexOf('@');
                if (pos > -1)
                    // CREATE DOCUMENT
                    return new ODocument(iFieldValueAsString.substring(1, pos), new ORecordId(iFieldValueAsString.substring(pos + 1)));
                else {
                    // CREATE SIMPLE RID
                    return new ORecordId(iFieldValueAsString);
                }
            case EMBEDDED:
                return fromString(iFieldValueAsString);
            case DATE:
                if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
                    return null;
                try {
                    // TRY TO PARSE AS LONG
                    return Long.parseLong(iFieldValueAsString);
                } catch (NumberFormatException e) {
                    try {
                        // TRY TO PARSE AS DATE
                        return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString);
                    } catch (ParseException ex) {
                        throw OException.wrapException(new OSerializationException("Unable to unmarshall date (format=" + ODateHelper.getDateFormat() + ") : " + iFieldValueAsString), e);
                    }
                }
            case DATETIME:
                if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
                    return null;
                try {
                    // TRY TO PARSE AS LONG
                    return Long.parseLong(iFieldValueAsString);
                } catch (NumberFormatException e) {
                    try {
                        // TRY TO PARSE AS DATETIME
                        return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString);
                    } catch (ParseException ex) {
                        throw OException.wrapException(new OSerializationException("Unable to unmarshall datetime (format=" + ODateHelper.getDateTimeFormat() + ") : " + iFieldValueAsString), e);
                    }
                }
            case BINARY:
                return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValueAsString);
            case CUSTOM:
                {
                    try {
                        ByteArrayInputStream bais = new ByteArrayInputStream(OBase64Utils.decode(iFieldValueAsString));
                        ObjectInputStream input = new ObjectInputStream(bais);
                        return input.readObject();
                    } catch (IOException e) {
                        throw OException.wrapException(new OSerializationException("Error on custom field deserialization"), e);
                    } catch (ClassNotFoundException e) {
                        throw OException.wrapException(new OSerializationException("Error on custom field deserialization"), e);
                    }
                }
            default:
                return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValue);
        }
    return iFieldValueAsString;
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) IOException(java.io.IOException) ORecordId(com.orientechnologies.orient.core.id.ORecordId) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseException(java.text.ParseException) ObjectInputStream(java.io.ObjectInputStream)

Example 25 with OSerializationException

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

the class ORecordSerializerSchemaAware2CSV method fromString.

@Override
public ORecord fromString(String iContent, final ORecord iRecord, final String[] iFields) {
    iContent = iContent.trim();
    if (iContent.length() == 0)
        return iRecord;
    // UNMARSHALL THE CLASS NAME
    final ODocument record = (ODocument) iRecord;
    int pos;
    final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
    final int posFirstValue = iContent.indexOf(OStringSerializerHelper.ENTRY_SEPARATOR);
    pos = iContent.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
    if (pos > -1 && (pos < posFirstValue || posFirstValue == -1)) {
        if ((record.getIdentity().getClusterId() < 0 || database == null || !database.getStorageVersions().classesAreDetectedByClusterId()))
            ODocumentInternal.fillClassNameIfNeeded(((ODocument) iRecord), iContent.substring(0, pos));
        iContent = iContent.substring(pos + 1);
    } else
        record.setClassNameIfExists(null);
    if (iFields != null && iFields.length == 1 && iFields[0].equals("@class"))
        // ONLY THE CLASS NAME HAS BEEN REQUESTED: RETURN NOW WITHOUT UNMARSHALL THE ENTIRE RECORD
        return iRecord;
    final List<String> fields = OStringSerializerHelper.smartSplit(iContent, OStringSerializerHelper.RECORD_SEPARATOR, true, true);
    String fieldName = null;
    String fieldValue;
    OType type;
    OClass linkedClass;
    OType linkedType;
    OProperty prop;
    final Set<String> fieldSet;
    if (iFields != null && iFields.length > 0) {
        fieldSet = new HashSet<String>(iFields.length);
        for (String f : iFields) fieldSet.add(f);
    } else
        fieldSet = null;
    // UNMARSHALL ALL THE FIELDS
    for (String fieldEntry : fields) {
        fieldEntry = fieldEntry.trim();
        boolean uncertainType = false;
        try {
            pos = fieldEntry.indexOf(FIELD_VALUE_SEPARATOR);
            if (pos > -1) {
                // GET THE FIELD NAME
                fieldName = fieldEntry.substring(0, pos);
                // CHECK IF THE FIELD IS REQUESTED TO BEING UNMARSHALLED
                if (fieldSet != null && !fieldSet.contains(fieldName))
                    continue;
                if (record.containsField(fieldName))
                    // ALREADY UNMARSHALLED: DON'T OVERWRITE IT
                    continue;
                // GET THE FIELD VALUE
                fieldValue = fieldEntry.length() > pos + 1 ? fieldEntry.substring(pos + 1) : null;
                boolean setFieldType = false;
                // SEARCH FOR A CONFIGURED PROPERTY
                prop = ODocumentInternal.getImmutableSchemaClass(record) != null ? ODocumentInternal.getImmutableSchemaClass(record).getProperty(fieldName) : null;
                if (prop != null && prop.getType() != OType.ANY) {
                    // RECOGNIZED PROPERTY
                    type = prop.getType();
                    linkedClass = prop.getLinkedClass();
                    linkedType = prop.getLinkedType();
                } else {
                    // SCHEMA PROPERTY NOT FOUND FOR THIS FIELD: TRY TO AUTODETERMINE THE BEST TYPE
                    type = record.fieldType(fieldName);
                    if (type == OType.ANY)
                        type = null;
                    if (type != null)
                        setFieldType = true;
                    linkedClass = null;
                    linkedType = null;
                    // NOT FOUND: TRY TO DETERMINE THE TYPE FROM ITS CONTENT
                    if (fieldValue != null && type == null) {
                        if (fieldValue.length() > 1 && fieldValue.charAt(0) == '"' && fieldValue.charAt(fieldValue.length() - 1) == '"') {
                            type = OType.STRING;
                        } else if (fieldValue.startsWith(OStringSerializerHelper.LINKSET_PREFIX)) {
                            type = OType.LINKSET;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN && fieldValue.charAt(fieldValue.length() - 1) == OStringSerializerHelper.LIST_END || fieldValue.charAt(0) == OStringSerializerHelper.SET_BEGIN && fieldValue.charAt(fieldValue.length() - 1) == OStringSerializerHelper.SET_END) {
                            // EMBEDDED LIST/SET
                            type = fieldValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN ? OType.EMBEDDEDLIST : OType.EMBEDDEDSET;
                            final String value = fieldValue.substring(1, fieldValue.length() - 1);
                            if (!value.isEmpty()) {
                                if (value.charAt(0) == OStringSerializerHelper.LINK) {
                                    // TODO replace with regex
                                    // ASSURE ALL THE ITEMS ARE RID
                                    int max = value.length();
                                    boolean allLinks = true;
                                    boolean checkRid = true;
                                    for (int i = 0; i < max; ++i) {
                                        char c = value.charAt(i);
                                        if (checkRid) {
                                            if (c != '#') {
                                                allLinks = false;
                                                break;
                                            }
                                            checkRid = false;
                                        } else if (c == ',')
                                            checkRid = true;
                                    }
                                    if (allLinks) {
                                        type = fieldValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN ? OType.LINKLIST : OType.LINKSET;
                                        linkedType = OType.LINK;
                                    }
                                } else if (value.charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) {
                                    linkedType = OType.EMBEDDED;
                                } else if (value.charAt(0) == OStringSerializerHelper.CUSTOM_TYPE) {
                                    linkedType = OType.CUSTOM;
                                } else if (Character.isDigit(value.charAt(0)) || value.charAt(0) == '+' || value.charAt(0) == '-') {
                                    String[] items = value.split(",");
                                    linkedType = getType(items[0]);
                                } else if (value.charAt(0) == '\'' || value.charAt(0) == '"')
                                    linkedType = OType.STRING;
                            } else
                                uncertainType = true;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.MAP_BEGIN && fieldValue.charAt(fieldValue.length() - 1) == OStringSerializerHelper.MAP_END) {
                            type = OType.EMBEDDEDMAP;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.LINK)
                            type = OType.LINK;
                        else if (fieldValue.charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) {
                            // TEMPORARY PATCH
                            if (fieldValue.startsWith("(ORIDs"))
                                type = OType.LINKSET;
                            else
                                type = OType.EMBEDDED;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.BAG_BEGIN) {
                            type = OType.LINKBAG;
                        } else if (fieldValue.equals("true") || fieldValue.equals("false"))
                            type = OType.BOOLEAN;
                        else
                            type = getType(fieldValue);
                    }
                }
                final Object value = fieldFromStream(iRecord, type, linkedClass, linkedType, fieldName, fieldValue);
                if ("@class".equals(fieldName)) {
                    ODocumentInternal.fillClassNameIfNeeded(((ODocument) iRecord), value.toString());
                } else {
                    record.field(fieldName, value, type);
                }
                if (uncertainType)
                    record.setFieldType(fieldName, null);
            }
        } catch (Exception e) {
            throw OException.wrapException(new OSerializationException("Error on unmarshalling field '" + fieldName + "' in record " + iRecord.getIdentity() + " with value: " + fieldEntry), e);
        }
    }
    return iRecord;
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OType(com.orientechnologies.orient.core.metadata.schema.OType) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) OException(com.orientechnologies.common.exception.OException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) 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