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 context the expression context
035     */
036    public StringWildcardExpression(String metadata, String value, ExpressionContext context)
037    {
038        _value = value;
039        _metadata = new MetadataExpression(metadata, context);
040        _caseInsensitive = context.caseInsensitive();
041    }
042    
043    public String build()
044    {
045        if (_caseInsensitive)
046        {
047            return "jcr:like(fn:lower-case(" + _metadata.build() + "), '%" + _escapeValue(_value.toLowerCase()) + "%')";
048        }
049        else
050        {
051            return "jcr:like(" + _metadata.build() + ", '%" + _escapeValue(_value) + "%')";
052        }
053    }
054
055    private String _escapeValue(String value)
056    {
057        // First escape ' - " \ _ and %, Then escape ' into '' for XQuery compliance
058        return value.replaceAll("(['\\-_\"\\\\%])", "\\\\$1").replaceAll("'", "''");
059    }
060}