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