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