1 /*
2  * Copyright 2019-2020 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.springframework.data.jpa.repository.query;
17
18 import lombok.Value;
19
20 import java.util.Arrays;
21 import java.util.List;
22 import java.util.stream.Stream;
23
24 import org.springframework.lang.Nullable;
25
26 /**
27  * A value type encapsulating an escape character for LIKE queries and the actually usage of it in escaping
28  * {@link String}s.
29  *
30  * @author Jens Schauder
31  * @author Oliver Drotbohm
32  */

33 @Value(staticConstructor = "of")
34 public class EscapeCharacter {
35
36     public static final EscapeCharacter DEFAULT = EscapeCharacter.of('\\');
37     private static final List<String> TO_REPLACE = Arrays.asList("_""%");
38
39     char escapeCharacter;
40
41     /**
42      * Escapes all special like characters ({@code _}, {@code %}) using the configured escape character.
43      *
44      * @param value may be {@literal null}.
45      * @return
46      */

47     @Nullable
48     public String escape(@Nullable String value) {
49
50         return value == null //
51                 ? null //
52                 : Stream.concat(Stream.of(String.valueOf(escapeCharacter)), TO_REPLACE.stream()) //
53                         .reduce(value, (it, character) -> it.replace(character, this.escapeCharacter + character));
54     }
55 }
56