1 /*
2 * Copyright 2009-2021 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 * http://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.apache.ibatis.builder.annotation;
17
18 import java.lang.reflect.Method;
19 import java.util.Arrays;
20 import java.util.List;
21 import java.util.stream.Collectors;
22
23 import org.apache.ibatis.builder.BuilderException;
24
25 /**
26 * The interface that resolve an SQL provider method via an SQL provider class.
27 *
28 * <p> This interface need to implements at an SQL provider class and
29 * it need to define the default constructor for creating a new instance.
30 *
31 * @since 3.5.1
32 * @author Kazuki Shimizu
33 */
34 public interface ProviderMethodResolver {
35
36 /**
37 * Resolve an SQL provider method.
38 *
39 * <p> The default implementation return a method that matches following conditions.
40 * <ul>
41 * <li>Method name matches with mapper method</li>
42 * <li>Return type matches the {@link CharSequence}({@link String}, {@link StringBuilder}, etc...)</li>
43 * </ul>
44 * If matched method is zero or multiple, it throws a {@link BuilderException}.
45 *
46 * @param context a context for SQL provider
47 * @return an SQL provider method
48 * @throws BuilderException Throws when cannot resolve a target method
49 */
50 default Method resolveMethod(ProviderContext context) {
51 List<Method> sameNameMethods = Arrays.stream(getClass().getMethods())
52 .filter(m -> m.getName().equals(context.getMapperMethod().getName()))
53 .collect(Collectors.toList());
54 if (sameNameMethods.isEmpty()) {
55 throw new BuilderException("Cannot resolve the provider method because '"
56 + context.getMapperMethod().getName() + "' not found in SqlProvider '" + getClass().getName() + "'.");
57 }
58 List<Method> targetMethods = sameNameMethods.stream()
59 .filter(m -> CharSequence.class.isAssignableFrom(m.getReturnType()))
60 .collect(Collectors.toList());
61 if (targetMethods.size() == 1) {
62 return targetMethods.get(0);
63 }
64 if (targetMethods.isEmpty()) {
65 throw new BuilderException("Cannot resolve the provider method because '"
66 + context.getMapperMethod().getName() + "' does not return the CharSequence or its subclass in SqlProvider '"
67 + getClass().getName() + "'.");
68 } else {
69 throw new BuilderException("Cannot resolve the provider method because '"
70 + context.getMapperMethod().getName() + "' is found multiple in SqlProvider '" + getClass().getName() + "'.");
71 }
72 }
73
74 }