Search in sources :

Example 1 with OType

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

the class OStorageConfiguration method fromStream.

public void fromStream(final byte[] stream, int offset, int length) {
    clear();
    final String[] values = new String(stream, offset, length).split("\\|");
    int index = 0;
    version = Integer.parseInt(read(values[index++]));
    name = read(values[index++]);
    schemaRecordId = read(values[index++]);
    dictionaryRecordId = read(values[index++]);
    if (version > 0)
        indexMgrRecordId = read(values[index++]);
    else
        // @COMPATIBILITY
        indexMgrRecordId = null;
    localeLanguage = read(values[index++]);
    localeCountry = read(values[index++]);
    dateFormat = read(values[index++]);
    dateTimeFormat = read(values[index++]);
    // @COMPATIBILITY 1.2.0
    if (version >= 4) {
        timeZone = TimeZone.getTimeZone(read(values[index++]));
        charset = read(values[index++]);
    }
    final ORecordConflictStrategyFactory conflictStrategyFactory = Orient.instance().getRecordConflictStrategy();
    if (version >= 12)
        conflictStrategy = conflictStrategyFactory.getStrategy(read(values[index++])).getName();
    else
        conflictStrategy = conflictStrategyFactory.getDefaultStrategy();
    // @COMPATIBILITY
    if (version > 1)
        index = phySegmentFromStream(values, index, fileTemplate);
    int size = Integer.parseInt(read(values[index++]));
    // PREPARE THE LIST OF CLUSTERS
    clusters.clear();
    String determineStorageCompression = null;
    for (int i = 0; i < size; ++i) {
        final int clusterId = Integer.parseInt(read(values[index++]));
        if (clusterId == -1)
            continue;
        final String clusterName = read(values[index++]);
        final int targetDataSegmentId = version >= 3 ? Integer.parseInt(read(values[index++])) : 0;
        final String clusterType = read(values[index++]);
        final OStorageClusterConfiguration currentCluster;
        if (clusterType.equals("d")) {
            final boolean cc = Boolean.valueOf(read(values[index++]));
            final float bb = Float.valueOf(read(values[index++]));
            final float aa = Float.valueOf(read(values[index++]));
            final String clusterCompression = read(values[index++]);
            if (determineStorageCompression == null)
                // TRY TO DETERMINE THE STORAGE COMPRESSION. BEFORE VERSION 11 IT WASN'T STORED IN STORAGE CFG, SO GET FROM THE FIRST
                // CLUSTER
                determineStorageCompression = clusterCompression;
            String clusterEncryption = null;
            if (version >= 15)
                clusterEncryption = read(values[index++]);
            final String clusterConflictStrategy;
            if (version >= 12)
                clusterConflictStrategy = read(values[index++]);
            else
                // INHERIT THE STRATEGY IN STORAGE
                clusterConflictStrategy = null;
            OStorageClusterConfiguration.STATUS status = OStorageClusterConfiguration.STATUS.ONLINE;
            if (version >= 13)
                status = OStorageClusterConfiguration.STATUS.valueOf(read(values[index++]));
            currentCluster = new OStoragePaginatedClusterConfiguration(this, clusterId, clusterName, null, cc, bb, aa, clusterCompression, clusterEncryption, configuration.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY), clusterConflictStrategy, status);
        } else if (clusterType.equals("p"))
            // PHYSICAL CLUSTER
            throw new IllegalArgumentException("Cluster of storage 'local' are not supported since 2.0");
        else
            throw new IllegalArgumentException("Unsupported cluster type: " + clusterType);
        // MAKE ROOMS, EVENTUALLY FILLING EMPTIES ENTRIES
        for (int c = clusters.size(); c <= clusterId; ++c) clusters.add(null);
        clusters.set(clusterId, currentCluster);
    }
    if (version < 13) {
        // OLD: READ DATA-SEGMENTS
        size = Integer.parseInt(read(values[index++]));
        for (int i = 0; i < size; ++i) {
            int dataId = Integer.parseInt(read(values[index++]));
            if (dataId == -1)
                continue;
            read(values[index++]);
            read(values[index++]);
            read(values[index++]);
            read(values[index++]);
        }
        // READ TX_SEGMENT STUFF
        read(values[index++]);
        read(values[index++]);
        read(values[index++]);
        read(values[index++]);
        read(values[index++]);
    }
    size = Integer.parseInt(read(values[index++]));
    clearProperties();
    for (int i = 0; i < size; ++i) setProperty(read(values[index++]), read(values[index++]));
    if (version >= 7)
        binaryFormatVersion = Integer.parseInt(read(values[index++]));
    else if (version == 6)
        binaryFormatVersion = 9;
    else
        binaryFormatVersion = 8;
    if (version >= 8)
        clusterSelection = read(values[index++]);
    else
        // DEFAULT = ROUND-ROBIN
        clusterSelection = ORoundRobinClusterSelectionStrategy.NAME;
    if (version >= 9)
        setMinimumClusters(Integer.parseInt(read(values[index++])));
    else
        // DEFAULT = 1
        setMinimumClusters(1);
    autoInitClusters();
    if (version >= 10) {
        recordSerializer = read(values[index++]);
        recordSerializerVersion = Integer.parseInt(read(values[index++]));
    }
    if (version >= 11) {
        // READ THE CONFIGURATION
        final int cfgSize = Integer.parseInt(read(values[index++]));
        for (int i = 0; i < cfgSize; ++i) {
            final String key = read(values[index++]);
            final Object value = read(values[index++]);
            final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key);
            if (cfg != null) {
                if (value != null)
                    configuration.setValue(key, OType.convert(value, cfg.getType()));
            } else
                OLogManager.instance().warn(this, "Ignored storage configuration because not supported: %s=%s", key, value);
        }
    } else
        // SAVE STORAGE COMPRESSION METHOD AS PROPERTY
        configuration.setValue(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD, determineStorageCompression);
    if (version > 15) {
        final int enginesSize = Integer.parseInt(read(values[index++]));
        for (int i = 0; i < enginesSize; i++) {
            final String name = read(values[index++]);
            final String algorithm = read(values[index++]);
            final String indexType;
            if (version > 16)
                indexType = read(values[index++]);
            else
                indexType = "";
            final byte valueSerializerId = Byte.parseByte(read(values[index++]));
            final byte keySerializerId = Byte.parseByte(read(values[index++]));
            final boolean isAutomatic = Boolean.parseBoolean(read((values[index++])));
            final Boolean durableInNonTxMode;
            if (read(values[index]) == null) {
                durableInNonTxMode = null;
                index++;
            } else
                durableInNonTxMode = Boolean.parseBoolean(read(values[index++]));
            final int version = Integer.parseInt(read(values[index++]));
            final boolean nullValuesSupport = Boolean.parseBoolean(read((values[index++])));
            final int keySize = Integer.parseInt(read(values[index++]));
            final int typesLength = Integer.parseInt(read(values[index++]));
            final OType[] types = new OType[typesLength];
            for (int n = 0; n < types.length; n++) {
                final OType type = OType.valueOf(read(values[index++]));
                types[n] = type;
            }
            final int propertiesSize = Integer.parseInt(read(values[index++]));
            final Map<String, String> engineProperties;
            if (propertiesSize == 0)
                engineProperties = null;
            else {
                engineProperties = new HashMap<String, String>(propertiesSize);
                for (int n = 0; n < propertiesSize; n++) {
                    final String key = read(values[index++]);
                    final String value = read(values[index++]);
                    engineProperties.put(key, value);
                }
            }
            final IndexEngineData indexEngineData = new IndexEngineData(name, algorithm, indexType, durableInNonTxMode, version, valueSerializerId, keySerializerId, isAutomatic, types, nullValuesSupport, keySize, engineProperties);
            indexEngines.put(name.toLowerCase(getLocaleInstance()), indexEngineData);
        }
    }
}
Also used : OType(com.orientechnologies.orient.core.metadata.schema.OType) ORecordConflictStrategyFactory(com.orientechnologies.orient.core.conflict.ORecordConflictStrategyFactory)

Example 2 with OType

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

the class OStorageConfiguration method toStream.

/**
   * Added version used for managed Network Versioning.
   *
   * @param iNetworkVersion
   * @return
   * @throws OSerializationException
   */
public byte[] toStream(final int iNetworkVersion) throws OSerializationException {
    final StringBuilder buffer = new StringBuilder(8192);
    write(buffer, CURRENT_VERSION);
    write(buffer, name);
    write(buffer, schemaRecordId);
    write(buffer, dictionaryRecordId);
    write(buffer, indexMgrRecordId);
    write(buffer, localeLanguage);
    write(buffer, localeCountry);
    write(buffer, dateFormat);
    write(buffer, dateTimeFormat);
    write(buffer, timeZone.getID());
    write(buffer, charset);
    if (iNetworkVersion > 24)
        write(buffer, conflictStrategy);
    phySegmentToStream(buffer, fileTemplate);
    write(buffer, clusters.size());
    for (OStorageClusterConfiguration c : clusters) {
        if (c == null) {
            write(buffer, -1);
            continue;
        }
        write(buffer, c.getId());
        write(buffer, c.getName());
        write(buffer, c.getDataSegmentId());
        if (c instanceof OStoragePaginatedClusterConfiguration) {
            write(buffer, "d");
            final OStoragePaginatedClusterConfiguration paginatedClusterConfiguration = (OStoragePaginatedClusterConfiguration) c;
            write(buffer, paginatedClusterConfiguration.useWal);
            write(buffer, paginatedClusterConfiguration.recordOverflowGrowFactor);
            write(buffer, paginatedClusterConfiguration.recordGrowFactor);
            write(buffer, paginatedClusterConfiguration.compression);
            if (iNetworkVersion >= 31)
                write(buffer, paginatedClusterConfiguration.encryption);
            if (iNetworkVersion > 24)
                write(buffer, paginatedClusterConfiguration.conflictStrategy);
            if (iNetworkVersion > 25)
                write(buffer, paginatedClusterConfiguration.getStatus().name().toString());
        }
    }
    if (iNetworkVersion <= 25) {
        // dataSegment array
        write(buffer, 0);
        // tx Segment File
        write(buffer, "");
        write(buffer, "");
        write(buffer, 0);
        // tx segment flags
        write(buffer, false);
        write(buffer, false);
    }
    synchronized (properties) {
        write(buffer, properties.size());
        for (OStorageEntryConfiguration e : properties) entryToStream(buffer, e);
    }
    write(buffer, binaryFormatVersion);
    write(buffer, clusterSelection);
    write(buffer, getMinimumClusters());
    if (iNetworkVersion > 24) {
        write(buffer, recordSerializer);
        write(buffer, recordSerializerVersion);
        // WRITE CONFIGURATION
        write(buffer, configuration.getContextSize());
        for (String k : configuration.getContextKeys()) {
            final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(k);
            write(buffer, k);
            write(buffer, cfg.isHidden() ? null : configuration.getValueAsString(cfg));
        }
    }
    write(buffer, indexEngines.size());
    for (IndexEngineData engineData : indexEngines.values()) {
        write(buffer, engineData.name);
        write(buffer, engineData.algorithm);
        write(buffer, engineData.indexType == null ? "" : engineData.indexType);
        write(buffer, engineData.valueSerializerId);
        write(buffer, engineData.keySerializedId);
        write(buffer, engineData.isAutomatic);
        write(buffer, engineData.durableInNonTxMode);
        write(buffer, engineData.version);
        write(buffer, engineData.nullValuesSupport);
        write(buffer, engineData.keySize);
        if (engineData.keyTypes != null) {
            write(buffer, engineData.keyTypes.length);
            for (OType type : engineData.keyTypes) {
                write(buffer, type.name());
            }
        } else {
            write(buffer, 0);
        }
        if (engineData.engineProperties == null) {
            write(buffer, 0);
        } else {
            write(buffer, engineData.engineProperties.size());
            for (Map.Entry<String, String> property : engineData.engineProperties.entrySet()) {
                write(buffer, property.getKey());
                write(buffer, property.getValue());
            }
        }
    }
    // PLAIN: ALLOCATE ENOUGH SPACE TO REUSE IT EVERY TIME
    buffer.append("|");
    return buffer.toString().getBytes();
}
Also used : OType(com.orientechnologies.orient.core.metadata.schema.OType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 3 with OType

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

the class OPropertyValueValidator method validate.

@Override
public void validate(IValidatable<T> validatable) {
    T fieldValue = validatable.getValue();
    OProperty p = getProperty();
    if (fieldValue == null) {
        if (p.isNotNull()) {
            validatable.error(newValidationError("required"));
        } else if (p.isMandatory() && Strings.isEmpty(p.getDefaultValue())) {
            ODocument doc = getDocument();
            // If doc is not defined: lets assume that mandatory fields must be not null
            if (doc == null || !doc.containsField(p.getName())) {
                validatable.error(newValidationError("mandatory"));
            }
        }
    } else {
        OType type = p.getType();
        switch(type) {
            case LINK:
                validateLink(validatable, p, fieldValue);
                break;
            case LINKLIST:
                if (!(fieldValue instanceof List))
                    validatable.error(newValidationError("wrongtype"));
                else if (p.getLinkedClass() != null)
                    for (Object item : ((List<?>) fieldValue)) validateLink(validatable, p, item);
                break;
            case LINKSET:
                if (!(fieldValue instanceof Collection))
                    validatable.error(newValidationError("wrongtype"));
                else if (p.getLinkedClass() != null)
                    for (Object item : ((Collection<?>) fieldValue)) validateLink(validatable, p, item);
                break;
            case LINKMAP:
                if (!(fieldValue instanceof Map))
                    validatable.error(newValidationError("wrongtype"));
                else if (p.getLinkedClass() != null)
                    for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet()) validateLink(validatable, p, entry.getValue());
                break;
            case EMBEDDED:
                validateEmbedded(validatable, p, fieldValue);
                break;
            case EMBEDDEDLIST:
                if (!(fieldValue instanceof List))
                    validatable.error(newValidationError("wrongtype"));
                else if (p.getLinkedClass() != null) {
                    for (Object item : ((List<?>) fieldValue)) validateEmbedded(validatable, p, item);
                } else if (p.getLinkedType() != null) {
                    for (Object item : ((List<?>) fieldValue)) validateType(validatable, p, item);
                }
                break;
            case EMBEDDEDSET:
                if (!(fieldValue instanceof Set))
                    validatable.error(newValidationError("wrongtype"));
                else if (p.getLinkedClass() != null) {
                    for (Object item : ((Set<?>) fieldValue)) validateEmbedded(validatable, p, item);
                } else if (p.getLinkedType() != null) {
                    for (Object item : ((Set<?>) fieldValue)) validateType(validatable, p, item);
                }
                break;
            case EMBEDDEDMAP:
                if (!(fieldValue instanceof Map))
                    validatable.error(newValidationError("wrongtype"));
                else if (p.getLinkedClass() != null) {
                    for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet()) validateEmbedded(validatable, p, entry.getValue());
                } else if (p.getLinkedType() != null) {
                    for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet()) validateType(validatable, p, entry.getValue());
                }
                break;
            default:
                break;
        }
        if (p.getMin() != null) {
            // MIN
            final String min = p.getMin();
            if (p.getType().equals(OType.STRING) && (fieldValue != null && ((String) fieldValue).length() < Integer.parseInt(min)))
                validatable.error(newValidationError("minviolationString", "min", min));
            else if (p.getType().equals(OType.BINARY) && (fieldValue != null && ((byte[]) fieldValue).length < Integer.parseInt(min)))
                validatable.error(newValidationError("minviolationBin", "min", min));
            else if (p.getType().equals(OType.INTEGER) && (fieldValue != null && type.asInt(fieldValue) < Integer.parseInt(min)))
                validatable.error(newValidationError("minviolation", "min", min));
            else if (p.getType().equals(OType.LONG) && (fieldValue != null && type.asLong(fieldValue) < Long.parseLong(min)))
                validatable.error(newValidationError("minviolation", "min", min));
            else if (p.getType().equals(OType.FLOAT) && (fieldValue != null && type.asFloat(fieldValue) < Float.parseFloat(min)))
                validatable.error(newValidationError("minviolation", "min", min));
            else if (p.getType().equals(OType.DOUBLE) && (fieldValue != null && type.asDouble(fieldValue) < Double.parseDouble(min)))
                validatable.error(newValidationError("minviolation", "min", min));
            else if (p.getType().equals(OType.DATE)) {
                try {
                    if (fieldValue != null && ((Date) fieldValue).before(getDatabase().getStorage().getConfiguration().getDateFormatInstance().parse(min)))
                        validatable.error(newValidationError("minviolationDate", "min", min));
                } catch (ParseException e) {
                /*NOP*/
                }
            } else if (p.getType().equals(OType.DATETIME)) {
                try {
                    if (fieldValue != null && ((Date) fieldValue).before(getDatabase().getStorage().getConfiguration().getDateTimeFormatInstance().parse(min)))
                        validatable.error(newValidationError("minviolationDate", "min", min));
                } catch (ParseException e) {
                /*NOP*/
                }
            } else if ((p.getType().equals(OType.EMBEDDEDLIST) || p.getType().equals(OType.EMBEDDEDSET) || p.getType().equals(OType.LINKLIST) || p.getType().equals(OType.LINKSET)) && (fieldValue != null && ((Collection<?>) fieldValue).size() < Integer.parseInt(min)))
                validatable.error(newValidationError("minviolationCollection", "min", min));
        }
        if (p.getMax() != null) {
            // MAX
            final String max = p.getMax();
            if (p.getType().equals(OType.STRING) && (fieldValue != null && ((String) fieldValue).length() > Integer.parseInt(max)))
                validatable.error(newValidationError("maxviolationString", "max", max));
            else if (p.getType().equals(OType.BINARY) && (fieldValue != null && ((byte[]) fieldValue).length > Integer.parseInt(max)))
                validatable.error(newValidationError("maxviolationBin", "max", max));
            else if (p.getType().equals(OType.INTEGER) && (fieldValue != null && type.asInt(fieldValue) > Integer.parseInt(max)))
                validatable.error(newValidationError("maxviolation", "max", max));
            else if (p.getType().equals(OType.LONG) && (fieldValue != null && type.asLong(fieldValue) > Long.parseLong(max)))
                validatable.error(newValidationError("maxviolation", "max", max));
            else if (p.getType().equals(OType.FLOAT) && (fieldValue != null && type.asFloat(fieldValue) > Float.parseFloat(max)))
                validatable.error(newValidationError("maxviolation", "max", max));
            else if (p.getType().equals(OType.DOUBLE) && (fieldValue != null && type.asDouble(fieldValue) > Double.parseDouble(max)))
                validatable.error(newValidationError("maxviolation", "max", max));
            else if (p.getType().equals(OType.DATE)) {
                try {
                    if (fieldValue != null && ((Date) fieldValue).before(getDatabase().getStorage().getConfiguration().getDateFormatInstance().parse(max)))
                        validatable.error(newValidationError("maxviolationDate", "max", max));
                } catch (ParseException e) {
                /*NOP*/
                }
            } else if (p.getType().equals(OType.DATETIME)) {
                try {
                    if (fieldValue != null && ((Date) fieldValue).before(getDatabase().getStorage().getConfiguration().getDateTimeFormatInstance().parse(max)))
                        validatable.error(newValidationError("maxviolationDate", "max", max));
                } catch (ParseException e) {
                /*NOP*/
                }
            } else if ((p.getType().equals(OType.EMBEDDEDLIST) || p.getType().equals(OType.EMBEDDEDSET) || p.getType().equals(OType.LINKLIST) || p.getType().equals(OType.LINKSET)) && (fieldValue != null && ((Collection<?>) fieldValue).size() > Integer.parseInt(max)))
                validatable.error(newValidationError("maxviolationCollection", "max", max));
        }
        if (p.getRegexp() != null && fieldValue != null) {
            String stringFieldValue = fieldValue.toString();
            if (!stringFieldValue.matches(p.getRegexp())) {
                validatable.error(newValidationError("regexpMismatch", "regexp", p.getRegexp()));
            }
        }
    }
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) Set(java.util.Set) OType(com.orientechnologies.orient.core.metadata.schema.OType) Date(java.util.Date) Entry(java.util.Map.Entry) Collection(java.util.Collection) List(java.util.List) ParseException(java.text.ParseException) Map(java.util.Map) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 4 with OType

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

the class OSecurityShared method createOrUpdateORoleClass.

private OClass createOrUpdateORoleClass(final ODatabaseDocument database, OClass identityClass) {
    OClass roleClass = database.getMetadata().getSchema().getClass("ORole");
    boolean unsafe = false;
    if (roleClass == null) {
        roleClass = database.getMetadata().getSchema().createClass("ORole", identityClass);
        unsafe = true;
    } else if (!roleClass.getSuperClasses().contains(identityClass))
        // MIGRATE AUTOMATICALLY TO 1.2.0
        roleClass.setSuperClasses(Arrays.asList(identityClass));
    if (!roleClass.existsProperty("name")) {
        roleClass.createProperty("name", OType.STRING, (OType) null, unsafe).setMandatory(true).setNotNull(true).setCollate("ci");
        roleClass.createIndex("ORole.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
    } else {
        final OProperty name = roleClass.getProperty("name");
        if (name.getAllIndexes().isEmpty())
            roleClass.createIndex("ORole.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
    }
    if (!roleClass.existsProperty("mode"))
        roleClass.createProperty("mode", OType.BYTE, (OType) null, unsafe);
    if (!roleClass.existsProperty("rules"))
        roleClass.createProperty("rules", OType.EMBEDDEDMAP, OType.BYTE, unsafe);
    if (!roleClass.existsProperty("inheritedRole"))
        roleClass.createProperty("inheritedRole", OType.LINK, roleClass, unsafe);
    return roleClass;
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OType(com.orientechnologies.orient.core.metadata.schema.OType)

Example 5 with OType

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

the class OCommandExecutorSQLSelect method searchInIndex.

private void searchInIndex() {
    final OIndex<Object> index = (OIndex<Object>) getDatabase().getMetadata().getIndexManager().getIndex(parsedTarget.getTargetIndex());
    if (index == null) {
        throw new OCommandExecutionException("Target index '" + parsedTarget.getTargetIndex() + "' not found");
    }
    boolean ascOrder = true;
    if (!orderedFields.isEmpty()) {
        if (orderedFields.size() != 1) {
            throw new OCommandExecutionException("Index can be ordered only by key field");
        }
        final String fieldName = orderedFields.get(0).getKey();
        if (!fieldName.equalsIgnoreCase("key")) {
            throw new OCommandExecutionException("Index can be ordered only by key field");
        }
        final String order = orderedFields.get(0).getValue();
        ascOrder = order.equalsIgnoreCase(KEYWORD_ASC);
    }
    // nothing was added yet, so index definition for manual index was not calculated
    if (index.getDefinition() == null) {
        return;
    }
    if (compiledFilter != null && compiledFilter.getRootCondition() != null) {
        if (!"KEY".equalsIgnoreCase(compiledFilter.getRootCondition().getLeft().toString())) {
            throw new OCommandExecutionException("'Key' field is required for queries against indexes");
        }
        final OQueryOperator indexOperator = compiledFilter.getRootCondition().getOperator();
        if (indexOperator instanceof OQueryOperatorBetween) {
            final Object[] values = (Object[]) compiledFilter.getRootCondition().getRight();
            final OIndexCursor cursor = index.iterateEntriesBetween(getIndexKey(index.getDefinition(), values[0], context), true, getIndexKey(index.getDefinition(), values[2], context), true, ascOrder);
            fetchEntriesFromIndexCursor(cursor);
        } else if (indexOperator instanceof OQueryOperatorMajor) {
            final Object value = compiledFilter.getRootCondition().getRight();
            final OIndexCursor cursor = index.iterateEntriesMajor(getIndexKey(index.getDefinition(), value, context), false, ascOrder);
            fetchEntriesFromIndexCursor(cursor);
        } else if (indexOperator instanceof OQueryOperatorMajorEquals) {
            final Object value = compiledFilter.getRootCondition().getRight();
            final OIndexCursor cursor = index.iterateEntriesMajor(getIndexKey(index.getDefinition(), value, context), true, ascOrder);
            fetchEntriesFromIndexCursor(cursor);
        } else if (indexOperator instanceof OQueryOperatorMinor) {
            final Object value = compiledFilter.getRootCondition().getRight();
            OIndexCursor cursor = index.iterateEntriesMinor(getIndexKey(index.getDefinition(), value, context), false, ascOrder);
            fetchEntriesFromIndexCursor(cursor);
        } else if (indexOperator instanceof OQueryOperatorMinorEquals) {
            final Object value = compiledFilter.getRootCondition().getRight();
            OIndexCursor cursor = index.iterateEntriesMinor(getIndexKey(index.getDefinition(), value, context), true, ascOrder);
            fetchEntriesFromIndexCursor(cursor);
        } else if (indexOperator instanceof OQueryOperatorIn) {
            final List<Object> origValues = (List<Object>) compiledFilter.getRootCondition().getRight();
            final List<Object> values = new ArrayList<Object>(origValues.size());
            for (Object val : origValues) {
                if (index.getDefinition() instanceof OCompositeIndexDefinition) {
                    throw new OCommandExecutionException("Operator IN not supported yet.");
                }
                val = getIndexKey(index.getDefinition(), val, context);
                values.add(val);
            }
            OIndexCursor cursor = index.iterateEntries(values, true);
            fetchEntriesFromIndexCursor(cursor);
        } else {
            final Object right = compiledFilter.getRootCondition().getRight();
            Object keyValue = getIndexKey(index.getDefinition(), right, context);
            if (keyValue == null) {
                return;
            }
            final Object res;
            if (index.getDefinition().getParamCount() == 1) {
                // CONVERT BEFORE SEARCH IF NEEDED
                final OType type = index.getDefinition().getTypes()[0];
                keyValue = OType.convert(keyValue, type.getDefaultJavaType());
                res = index.get(keyValue);
            } else {
                final Object secondKey = getIndexKey(index.getDefinition(), right, context);
                if (keyValue instanceof OCompositeKey && secondKey instanceof OCompositeKey && ((OCompositeKey) keyValue).getKeys().size() == index.getDefinition().getParamCount() && ((OCompositeKey) secondKey).getKeys().size() == index.getDefinition().getParamCount()) {
                    res = index.get(keyValue);
                } else {
                    OIndexCursor cursor = index.iterateEntriesBetween(keyValue, true, secondKey, true, true);
                    fetchEntriesFromIndexCursor(cursor);
                    return;
                }
            }
            if (res != null) {
                if (res instanceof Collection<?>) {
                    // MULTI VALUES INDEX
                    for (final OIdentifiable r : (Collection<OIdentifiable>) res) {
                        final ODocument record = createIndexEntryAsDocument(keyValue, r.getIdentity());
                        applyGroupBy(record, context);
                        if (!handleResult(record, context)) // LIMIT REACHED
                        {
                            break;
                        }
                    }
                } else {
                    // SINGLE VALUE INDEX
                    final ODocument record = createIndexEntryAsDocument(keyValue, ((OIdentifiable) res).getIdentity());
                    applyGroupBy(record, context);
                    handleResult(record, context);
                }
            }
        }
    } else {
        if (isIndexSizeQuery()) {
            getProjectionGroup(null, context).applyValue(projections.keySet().iterator().next(), index.getSize());
            return;
        }
        if (isIndexKeySizeQuery()) {
            getProjectionGroup(null, context).applyValue(projections.keySet().iterator().next(), index.getKeySize());
            return;
        }
        final OIndexInternal<?> indexInternal = index.getInternal();
        if (indexInternal instanceof OSharedResource) {
            ((OSharedResource) indexInternal).acquireExclusiveLock();
        }
        try {
            // ADD ALL THE ITEMS AS RESULT
            if (ascOrder) {
                final OIndexCursor cursor = index.cursor();
                fetchEntriesFromIndexCursor(cursor);
            } else {
                final OIndexCursor cursor = index.descCursor();
                fetchEntriesFromIndexCursor(cursor);
            }
        } finally {
            if (indexInternal instanceof OSharedResource) {
                ((OSharedResource) indexInternal).releaseExclusiveLock();
            }
        }
    }
}
Also used : OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) OType(com.orientechnologies.orient.core.metadata.schema.OType) OSharedResource(com.orientechnologies.common.concur.resource.OSharedResource)

Aggregations

OType (com.orientechnologies.orient.core.metadata.schema.OType)68 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)22 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)15 OProperty (com.orientechnologies.orient.core.metadata.schema.OProperty)15 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 Collection (java.util.Collection)6 Set (java.util.Set)6 ORecordLazyMultiValue (com.orientechnologies.orient.core.db.record.ORecordLazyMultiValue)5 ORecordLazySet (com.orientechnologies.orient.core.db.record.ORecordLazySet)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 ParseException (java.text.ParseException)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 Entry (java.util.Map.Entry)5 ORecordLazyMap (com.orientechnologies.orient.core.db.record.ORecordLazyMap)4