001/*
002 *  Copyright 2015 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
018/**
019 * Constructs an {@link Expression} corresponding to the wildcard comparison with a metadata,
020 * meaning that the {@link Expression} will search metadata containing the specified value.
021 * @deprecated use {@link StringExpression} instead.
022 */
023@Deprecated
024public class StringWildcardExpression implements Expression
025{
026    private String _value;
027    private MetadataExpression _metadata;
028    private boolean _caseInsensitive;
029
030    /**
031     * Creates the comparison Expression.
032     * @param metadata the metadata name.
033     * @param value the String value.
034     * @param caseInsensitive <code>true</code> if the search must be case insensitive.
035     */
036    public StringWildcardExpression(String metadata, String value, boolean caseInsensitive)
037    {
038        _value = value;
039        _metadata = new MetadataExpression(metadata);
040        _caseInsensitive = caseInsensitive;
041    }
042    
043    /**
044     * Creates the comparison Expression.
045     * @param metadata the metadata name.
046     * @param value the String value.
047     * @param caseInsensitive <code>true</code> if the search must be case insensitive.
048     * @param unversioned true if the metadata is unversioned, false otherwise.
049     */
050    public StringWildcardExpression(String metadata, String value, boolean caseInsensitive, boolean unversioned)
051    {
052        _value = value;
053        _metadata = new MetadataExpression(metadata, unversioned);
054        _caseInsensitive = caseInsensitive;
055    }
056
057    public String build()
058    {
059        if (_caseInsensitive)
060        {
061            return "jcr:like(fn:lower-case(" + _metadata.build() + "), '%" + _escapeValue(_value.toLowerCase()) + "%')";
062        }
063        else
064        {
065            return "jcr:like(" + _metadata.build() + ", '%" + _escapeValue(_value) + "%')";
066        }
067    }
068
069    private String _escapeValue(String value)
070    {
071        // First escape ' - " \ _ and %, Then escape ' into '' for XQuery compliance
072        return value.replaceAll("(['\\-_\"\\\\%])", "\\\\$1").replaceAll("'", "''");
073    }
074}