001/*
002 * (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019
020package org.nuxeo.ecm.directory.memory;
021
022import org.nuxeo.ecm.core.query.QueryParseException;
023import org.nuxeo.ecm.core.query.sql.model.Reference;
024import org.nuxeo.ecm.core.schema.SchemaManager;
025import org.nuxeo.ecm.core.schema.types.Field;
026import org.nuxeo.ecm.core.schema.types.Schema;
027import org.nuxeo.ecm.core.schema.types.primitives.BooleanType;
028import org.nuxeo.ecm.directory.Directory;
029import org.nuxeo.runtime.api.Framework;
030
031/**
032 * Evaluates an expression on a memory directory entry.
033 *
034 * @since 10.3
035 */
036public class MemoryDirectoryExpressionEvaluator extends MapExpressionEvaluator {
037
038    protected final String directoryName;
039
040    protected final Schema schema;
041
042    public MemoryDirectoryExpressionEvaluator(Directory directory) {
043        directoryName = directory.getName();
044        schema = Framework.getService(SchemaManager.class).getSchema(directory.getSchema());
045    }
046
047    @Override
048    protected QueryParseException unknownProperty(String name) {
049        return new QueryParseException("No column: " + name + " for directory: " + directoryName);
050    }
051
052    @Override
053    public Object walkReference(Reference ref) {
054        if (ref.cast != null) {
055            throw new QueryParseException("Cannot use cast: " + ref);
056        }
057        String name = ref.name;
058        Field field = schema.getField(name);
059        if (field == null) {
060            throw unknownProperty(name);
061        }
062        Object value = map.get(name);
063        if (field.getType() instanceof BooleanType) {
064            value = value == null ? null : (((Boolean) value).booleanValue() ? ONE : ZERO);
065        }
066        return value;
067    }
068
069}