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.support;
17
18 import lombok.RequiredArgsConstructor;
19
20 import org.springframework.data.jpa.repository.query.EscapeCharacter;
21 import org.springframework.data.spel.spi.EvaluationContextExtension;
22
23 /**
24 * {@link EvaluationContextExtension} to register {@link EscapeCharacter} as root object to essentially expose an
25 * {@code expose(…)} function to SpEL.
26 *
27 * @author Oliver Drotbohm
28 */
29 public class JpaEvaluationContextExtension implements EvaluationContextExtension {
30
31 private final JpaRootObject root;
32
33 /**
34 * Creates a new {@link JpaEvaluationContextExtension} for the given escape character.
35 *
36 * @param escapeCharacter the character to be used to escape parameters for LIKE expression.
37 */
38 public JpaEvaluationContextExtension(char escapeCharacter) {
39 this.root = JpaRootObject.of(EscapeCharacter.of(escapeCharacter));
40 }
41
42 /*
43 * (non-Javadoc)
44 * @see org.springframework.data.spel.spi.EvaluationContextExtension#getExtensionId()
45 */
46 @Override
47 public String getExtensionId() {
48 return "jpa";
49 }
50
51 /*
52 * (non-Javadoc)
53 * @see org.springframework.data.spel.spi.EvaluationContextExtension#getRootObject()
54 */
55 @Override
56 public Object getRootObject() {
57 return root;
58 }
59
60 @RequiredArgsConstructor(staticName = "of")
61 public static class JpaRootObject {
62
63 private final EscapeCharacter character;
64
65 /**
66 * Escapes the given source {@link String} for LIKE expressions.
67 *
68 * @param source can be {@literal null}.
69 * @return
70 * @see EscapeCharacter#escape(String)
71 */
72 public String escape(String source) {
73 return character.escape(source);
74 }
75
76 /**
77 * Returns the escape character being used to escape special characters for LIKE expressions.
78 *
79 * @return
80 */
81 public char escapeCharacter() {
82 return character.getEscapeCharacter();
83 }
84 }
85 }
86