1 /*
2  * Copyright 2018 The Android Open Source Project
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 androidx.room.solver.binderprovider
18 
19 import androidx.room.ext.GuavaUtilConcurrentTypeNames
20 import androidx.room.ext.RoomGuavaTypeNames
21 import androidx.room.ext.typeName
22 import androidx.room.parser.ParsedQuery
23 import androidx.room.processor.Context
24 import androidx.room.processor.ProcessorErrors
25 import androidx.room.solver.QueryResultBinderProvider
26 import androidx.room.solver.query.result.GuavaListenableFutureQueryResultBinder
27 import androidx.room.solver.query.result.QueryResultBinder
28 import javax.lang.model.type.DeclaredType
29 
30 class GuavaListenableFutureQueryResultBinderProvider(val context: Context)
31     : QueryResultBinderProvider {
32 
<lambda>null33     private val hasGuavaRoom by lazy {
34         context.processingEnv.elementUtils
35                 .getTypeElement(RoomGuavaTypeNames.GUAVA_ROOM.toString()) != null
36     }
37 
38     /**
39      * Returns the {@link GuavaListenableFutureQueryResultBinder} instance for the input type, if
40      * possible.
41      *
42      * <p>Emits a compiler error if the Guava Room extension library is not linked.
43      */
providenull44     override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
45         if (!hasGuavaRoom) {
46             context.logger.e(ProcessorErrors.MISSING_ROOM_GUAVA_ARTIFACT)
47         }
48 
49         // Use the type T inside ListenableFuture<T> as the type to adapt and to pass into
50         // the binder.
51         val adapter = context.typeAdapterStore.findQueryResultAdapter(
52                 declared.typeArguments.first(), query)
53         return GuavaListenableFutureQueryResultBinder(
54                 declared.typeArguments.first(), adapter)
55     }
56 
57     /**
58      * Returns true iff the input {@code declared} type is ListenableFuture<T>.
59      */
matchesnull60     override fun matches(declared: DeclaredType): Boolean =
61         declared.typeArguments.size == 1 &&
62                 context.processingEnv.typeUtils.erasure(declared).typeName() ==
63                         GuavaUtilConcurrentTypeNames.LISTENABLE_FUTURE
64 }
65