Search in sources :

Example 26 with OType

use of com.orientechnologies.orient.core.metadata.schema.OType 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 27 with OType

use of com.orientechnologies.orient.core.metadata.schema.OType in project orientdb by orientechnologies.

the class OAbstractPaginatedStorage method loadExternalIndexEngine.

public int loadExternalIndexEngine(String engineName, String algorithm, String indexType, OIndexDefinition indexDefinition, OBinarySerializer valueSerializer, boolean isAutomatic, Boolean durableInNonTxMode, int version, Map<String, String> engineProperties) {
    checkOpeness();
    stateLock.acquireWriteLock();
    try {
        checkOpeness();
        checkLowDiskSpaceFullCheckpointRequestsAndBackgroundDataFlushExceptions();
        // this method introduced for binary compatibility only
        if (configuration.binaryFormatVersion > 15)
            return -1;
        final String originalName = engineName;
        engineName = engineName.toLowerCase(configuration.getLocaleInstance());
        if (indexEngineNameMap.containsKey(engineName))
            throw new OIndexException("Index with name " + engineName + " already exists");
        makeStorageDirty();
        final OBinarySerializer keySerializer = determineKeySerializer(indexDefinition);
        final int keySize = determineKeySize(indexDefinition);
        final OType[] keyTypes = indexDefinition != null ? indexDefinition.getTypes() : null;
        final boolean nullValuesSupport = indexDefinition != null && !indexDefinition.isNullValuesIgnored();
        final OStorageConfiguration.IndexEngineData engineData = new OStorageConfiguration.IndexEngineData(originalName, algorithm, indexType, durableInNonTxMode, version, valueSerializer.getId(), keySerializer.getId(), isAutomatic, keyTypes, nullValuesSupport, keySize, engineProperties);
        final OIndexEngine engine = OIndexes.createIndexEngine(originalName, algorithm, indexType, durableInNonTxMode, this, version, engineProperties, null);
        engine.load(originalName, valueSerializer, isAutomatic, keySerializer, keyTypes, nullValuesSupport, keySize, engineData.getEngineProperties());
        indexEngineNameMap.put(engineName, engine);
        indexEngines.add(engine);
        configuration.addIndexEngine(engineName, engineData);
        return indexEngines.size() - 1;
    } catch (IOException e) {
        throw OException.wrapException(new OStorageException("Cannot add index engine " + engineName + " in storage."), e);
    } finally {
        stateLock.releaseWriteLock();
    }
}
Also used : OType(com.orientechnologies.orient.core.metadata.schema.OType) OStorageConfiguration(com.orientechnologies.orient.core.config.OStorageConfiguration) OBinarySerializer(com.orientechnologies.common.serialization.types.OBinarySerializer)

Example 28 with OType

use of com.orientechnologies.orient.core.metadata.schema.OType in project orientdb by orientechnologies.

the class OLuceneQueryBuilder method getQueryParser.

protected Query getQueryParser(OIndexDefinition index, String key, Analyzer analyzer) throws ParseException {
    String[] fields;
    if (index.isAutomatic()) {
        fields = index.getFields().toArray(new String[index.getFields().size()]);
    } else {
        int length = index.getTypes().length;
        fields = new String[length];
        for (int i = 0; i < length; i++) {
            fields[i] = "k" + i;
        }
    }
    Map<String, OType> types = new HashMap<String, OType>();
    for (int i = 0; i < fields.length; i++) {
        String field = fields[i];
        types.put(field, index.getTypes()[i]);
    }
    //    for (Map.Entry<String, OType> typeEntry : types.entrySet()) {
    //      System.out.println("typeEntry = " + typeEntry);
    //    }
    final OLuceneMultiFieldQueryParser queryParser = new OLuceneMultiFieldQueryParser(types, fields, analyzer);
    queryParser.setAllowLeadingWildcard(allowLeadingWildcard);
    queryParser.setLowercaseExpandedTerms(lowercaseExpandedTerms);
    try {
        return queryParser.parse(key);
    } catch (org.apache.lucene.queryparser.classic.ParseException e) {
        throw new ParseException(e.getMessage());
    }
}
Also used : OLuceneMultiFieldQueryParser(com.orientechnologies.lucene.parser.OLuceneMultiFieldQueryParser) HashMap(java.util.HashMap) OType(com.orientechnologies.orient.core.metadata.schema.OType) ParseException(com.orientechnologies.orient.core.sql.parser.ParseException)

Example 29 with OType

use of com.orientechnologies.orient.core.metadata.schema.OType in project orientdb by orientechnologies.

the class OrientJdbcResultSetMetaData method getColumnType.

public int getColumnType(final int column) throws SQLException {
    final ODocument currentRecord = getCurrentRecord();
    final String[] fieldNames = currentRecord.fieldNames();
    if (column > fieldNames.length)
        return Types.NULL;
    String fieldName = fieldNames[column - 1];
    // The OClass is not available so attempting to retrieve the OType from
    // the schema class
    // results in a NullPointerException
    // OClass oclass = currentRecord.getSchemaClass();
    OType otype = currentRecord.fieldType(fieldName);
    if (otype == null) {
        Object value = currentRecord.field(fieldName);
        if (value == null) {
            return Types.NULL;
        } else if (value instanceof OBlob) {
            // records
            return Types.BINARY;
        } else if (value instanceof ORecordLazyList) {
            ORecordLazyList list = (ORecordLazyList) value;
            // check if all the list items are instances of ORecordBytes
            ListIterator<OIdentifiable> iterator = list.listIterator();
            OIdentifiable listElement;
            boolean stop = false;
            while (iterator.hasNext() && !stop) {
                listElement = iterator.next();
                if (!(listElement instanceof OBlob))
                    stop = true;
            }
            if (!stop) {
                return Types.BLOB;
            }
        }
        return this.getSQLTypeFromJavaClass(value);
    } else {
        if (otype == OType.EMBEDDED || otype == OType.LINK) {
            Object value = currentRecord.field(fieldName);
            if (value == null) {
                return Types.NULL;
            }
            // 1. Check if the type is another record or a collection of records
            if (value instanceof OBlob) {
                return Types.BINARY;
            } else {
                // the default type
                return typesSqlTypes.get(otype);
            }
        } else {
            if (otype == OType.EMBEDDEDLIST || otype == OType.LINKLIST) {
                Object value = currentRecord.field(fieldName);
                if (value == null) {
                    return Types.NULL;
                }
                if (value instanceof ORecordLazyList) {
                    ORecordLazyList list = (ORecordLazyList) value;
                    // check if all the list items are instances of ORecordBytes
                    ListIterator<OIdentifiable> iterator = list.listIterator();
                    OIdentifiable listElement;
                    boolean stop = false;
                    while (iterator.hasNext() && !stop) {
                        listElement = iterator.next();
                        if (!(listElement instanceof OBlob))
                            stop = true;
                    }
                    if (stop) {
                        return typesSqlTypes.get(otype);
                    } else {
                        return Types.BLOB;
                    }
                } else {
                    return typesSqlTypes.get(otype);
                //            return Types.JAVA_OBJECT;
                }
            } else {
                return typesSqlTypes.get(otype);
            }
        }
    }
}
Also used : ORecordLazyList(com.orientechnologies.orient.core.db.record.ORecordLazyList) OBlob(com.orientechnologies.orient.core.record.impl.OBlob) OType(com.orientechnologies.orient.core.metadata.schema.OType) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 30 with OType

use of com.orientechnologies.orient.core.metadata.schema.OType in project orientdb by orientechnologies.

the class OQueryOperatorContainsValue method evaluateExpression.

@Override
@SuppressWarnings("unchecked")
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) {
    final OSQLFilterCondition condition;
    if (iCondition.getLeft() instanceof OSQLFilterCondition)
        condition = (OSQLFilterCondition) iCondition.getLeft();
    else if (iCondition.getRight() instanceof OSQLFilterCondition)
        condition = (OSQLFilterCondition) iCondition.getRight();
    else
        condition = null;
    OType type = null;
    if (iCondition.getLeft() instanceof OSQLFilterItemField && ((OSQLFilterItemField) iCondition.getLeft()).isFieldChain() && ((OSQLFilterItemField) iCondition.getLeft()).getFieldChain().getItemCount() == 1) {
        String fieldName = ((OSQLFilterItemField) iCondition.getLeft()).getFieldChain().getItemName(0);
        if (fieldName != null) {
            Object record = iRecord.getRecord();
            if (record instanceof ODocument) {
                OProperty property = ((ODocument) record).getSchemaClass().getProperty(fieldName);
                if (property != null && property.getType().isMultiValue()) {
                    type = property.getLinkedType();
                }
            }
        }
    }
    Object right = iRight;
    if (type != null) {
        right = OType.convert(iRight, type.getDefaultJavaType());
    }
    if (iLeft instanceof Map<?, ?>) {
        final Map<String, ?> map = (Map<String, ?>) iLeft;
        if (condition != null) {
            // CHECK AGAINST A CONDITION
            for (Object o : map.values()) {
                o = loadIfNeed(o);
                if ((Boolean) condition.evaluate((ODocument) o, null, iContext))
                    return true;
            }
        } else
            return map.containsValue(right);
    } else if (iRight instanceof Map<?, ?>) {
        final Map<String, ?> map = (Map<String, ?>) iRight;
        if (condition != null)
            // CHECK AGAINST A CONDITION
            for (Object o : map.values()) {
                o = loadIfNeed(o);
                if ((Boolean) condition.evaluate((ODocument) o, null, iContext))
                    return true;
                else
                    return map.containsValue(iLeft);
            }
    }
    return false;
}
Also used : OSQLFilterCondition(com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition) OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OSQLFilterItemField(com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField) OType(com.orientechnologies.orient.core.metadata.schema.OType) Map(java.util.Map) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OType (com.orientechnologies.orient.core.metadata.schema.OType)65 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)21 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)15 OProperty (com.orientechnologies.orient.core.metadata.schema.OProperty)14 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)12 ODatabaseObject (com.orientechnologies.orient.core.db.object.ODatabaseObject)11 Map (java.util.Map)10 OSerializationException (com.orientechnologies.orient.core.exception.OSerializationException)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 ORecordLazyList (com.orientechnologies.orient.core.db.record.ORecordLazyList)5 ORecordLazyMultiValue (com.orientechnologies.orient.core.db.record.ORecordLazyMultiValue)5 OTrackedMap (com.orientechnologies.orient.core.db.record.OTrackedMap)5 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)5 OBinarySerializerFactory (com.orientechnologies.orient.core.serialization.serializer.binary.OBinarySerializerFactory)5 Collection (java.util.Collection)5 ORecordLazyMap (com.orientechnologies.orient.core.db.record.ORecordLazyMap)4 ORecordLazySet (com.orientechnologies.orient.core.db.record.ORecordLazySet)4 OTrackedList (com.orientechnologies.orient.core.db.record.OTrackedList)4 ORID (com.orientechnologies.orient.core.id.ORID)4