001/* 002 * Copyright 2024 Anyware Services 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 */ 016package org.ametys.plugins.repository.query.expression; 017 018import java.util.ArrayList; 019import java.util.Arrays; 020import java.util.Collection; 021import java.util.Objects; 022import java.util.stream.Collectors; 023 024import org.apache.commons.lang.StringUtils; 025 026/** 027 * Constructs an {@link Expression} corresponding to a logical operator between several {@link Expression}. 028 */ 029public abstract class AbstractLogicalExpression extends ArrayList<Expression> implements Expression 030{ 031 /** 032 * Creates the logical expression. 033 * @param exprs the operands 034 */ 035 public AbstractLogicalExpression(Collection<Expression> exprs) 036 { 037 super(exprs); 038 } 039 040 /** 041 * Creates the logical expression. 042 * @param exprs the operands 043 */ 044 public AbstractLogicalExpression(Expression ... exprs) 045 { 046 super(Arrays.asList(exprs)); 047 } 048 049 public String build() 050 { 051 String logicalOperator = getLogicalOperator().toString(); 052 053 String joinExpression = this.stream() 054 .filter(Objects::nonNull) 055 .map(Expression::build) 056 .filter(StringUtils::isNotBlank) 057 .collect(Collectors.joining(logicalOperator)); 058 059 if (joinExpression.contains(logicalOperator)) 060 { 061 joinExpression = "(" + joinExpression + ")"; 062 } 063 064 return joinExpression; 065 } 066 067 /** 068 * Get the logicial operator to apply between operations, can contains spaces to separate the operator from the expressions. 069 * @return the operator to apply between each expressions 070 */ 071 protected abstract LogicalOperator getLogicalOperator(); 072}