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