1 /*
2  * Copyright (C) 2020 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 android.service.translation;
18 
19 import android.annotation.NonNull;
20 import android.os.DeadObjectException;
21 import android.os.RemoteException;
22 import android.util.Log;
23 import android.view.translation.TranslationResponse;
24 
25 import java.util.Objects;
26 import java.util.concurrent.atomic.AtomicBoolean;
27 import java.util.function.Consumer;
28 
29 /**
30  * Callback to receive the {@link TranslationResponse} on successful translation.
31  *
32  * @hide
33  */
34 final class OnTranslationResultCallbackWrapper implements
35         Consumer<TranslationResponse> {
36 
37     private static final String TAG = "OnTranslationResultCallback";
38 
39     private final @NonNull ITranslationCallback mCallback;
40 
41     private final AtomicBoolean mCalled;
42 
43     /**
44      * @hide
45      */
OnTranslationResultCallbackWrapper(@onNull ITranslationCallback callback)46     public OnTranslationResultCallbackWrapper(@NonNull ITranslationCallback callback) {
47         mCallback = Objects.requireNonNull(callback);
48         mCalled = new AtomicBoolean();
49     }
50 
51     @Override
accept(TranslationResponse response)52     public void accept(TranslationResponse response) {
53         assertNotCalled();
54         if (mCalled.getAndSet(response.isFinalResponse())) {
55             throw new IllegalStateException("Already called with complete response");
56         }
57 
58         try {
59             mCallback.onTranslationResponse(response);
60         } catch (RemoteException e) {
61             if (e instanceof DeadObjectException) {
62                 Log.w(TAG, "Process is dead, ignore.");
63                 return;
64             }
65             throw e.rethrowAsRuntimeException();
66         }
67     }
68 
assertNotCalled()69     private void assertNotCalled() {
70         if (mCalled.get()) {
71             throw new IllegalStateException("Already called");
72         }
73     }
74 }
75