All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.exasol.adapter.document.querypredicate.normalizer.LogicngToQueryPredicateConverter Maven / Gradle / Ivy

The newest version!
package com.exasol.adapter.document.querypredicate.normalizer;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.logicng.formulas.Formula;
import org.logicng.formulas.Literal;
import org.logicng.formulas.Variable;

import com.exasol.adapter.document.querypredicate.LogicalOperator;
import com.exasol.adapter.document.querypredicate.NoPredicate;
import com.exasol.adapter.document.querypredicate.NotPredicate;
import com.exasol.adapter.document.querypredicate.QueryPredicate;
import com.exasol.errorreporting.ExaError;

/**
 * This class converts LogicNG {@link Formula}s to {@link QueryPredicate} structures.
 */
class LogicngToQueryPredicateConverter {
    private final Map variablesMapping;

    /**
     * Create an instance of {@link LogicngToQueryPredicateConverter}.
     * 
     * @param variablesMapping variable map generated by {@link QueryPredicateToLogicngConverter}.
     */
    public LogicngToQueryPredicateConverter(final Map variablesMapping) {
        this.variablesMapping = variablesMapping;
    }

    /**
     * Converts LogicNG {@link Formula}s to {@link QueryPredicate} structures.
     * 
     * @param formula LogicNG formula
     * @return {@link QueryPredicate} structure
     */
    public QueryPredicate convert(final Formula formula) {
        switch (formula.type()) {
        case AND:
            return convertLogicOperator(LogicalOperator.Operator.AND, formula);
        case OR:
            return convertLogicOperator(LogicalOperator.Operator.OR, formula);
        case TRUE:
            return new NoPredicate();
        case LITERAL:
            return convertLiteral((Literal) formula);
        default:
            throw new IllegalStateException(ExaError.messageBuilder("F-VSD-29")
                    .message("Internal error (the formula {{FORULA}} has no corresponding QueryPredicate).")
                    .parameter("FORULA", formula.toString()).ticketMitigation().toString());
        }
    }

    private QueryPredicate convertLiteral(final Literal literal) {
        final QueryPredicate predicate = this.variablesMapping.get(literal.variable());
        if (literal.phase()) {
            return predicate;
        } else {
            return new NotPredicate(predicate);
        }
    }

    private LogicalOperator convertLogicOperator(final LogicalOperator.Operator operator, final Formula formula) {
        final Set operands = StreamSupport.stream(formula.spliterator(), false).map(this::convert)
                .collect(Collectors.toSet());
        return new LogicalOperator(operands, operator);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy