001/*
002 *  Copyright 2016 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.events;
017
018import org.ametys.plugins.repository.AmetysRepositoryException;
019import org.ametys.plugins.repository.query.expression.Expression;
020
021/**
022 * Constructs an {@link Expression} corresponding to a event'type comparison.
023 */
024public class EventTypeExpression implements Expression
025{
026    private Operator _operator;
027    private String[] _values;
028
029    /**
030     * Creates the expression.
031     * @param operator the operator to make the comparison (only Operator.EQ and Operator.NE allowed)
032     * @param value the tag value 
033     */
034    public EventTypeExpression(Operator operator, String value)
035    {
036        if (Operator.EQ != operator && Operator.NE != operator)
037        {
038            throw new AmetysRepositoryException("Test operator '" + "' is unknown for test's expression.");
039        }
040
041        _operator = operator;
042        _values = new String[]{value};
043    }
044    
045    /**
046     * Creates the expression.
047     * @param operator the operator to make the comparison (only Operator.EQ and Operator.NE allowed)
048     * @param values the events' type value 
049     */
050    public EventTypeExpression(Operator operator, String... values)
051    {
052        _operator = operator;
053        _values = values;
054    }
055    
056    @Override
057    public String build()
058    {
059        StringBuilder xpath = new StringBuilder();
060        
061        if (_values.length == 1)
062        {
063            xpath.append('@').append(EventType.EVENT_TYPE)
064                 .append(' ').append(_operator).append(" '").append(_values[0].replaceAll("'", "''")).append("'");
065            
066            return xpath.toString();
067        }
068        
069        xpath.append(Operator.EQ.equals(_operator) ? '(' : "not(");
070        
071        for (int i = 0; i < _values.length; i++)
072        {
073            if (i > 0)
074            {
075                xpath.append(" or ");
076            }
077            
078            xpath.append('@').append(EventType.EVENT_TYPE)
079                 .append(" = '").append(_values[i].replaceAll("'", "''")).append("'");
080        }
081        
082        xpath.append(')');
083        
084        return xpath.toString();
085    }
086}