aboutsummaryrefslogtreecommitdiff
path: root/third_party/sl4a/src/main/java/com/google/android/mobly/snippet/rpc/MethodDescriptor.java
blob: b9c8a7a54464f30df15ba54f3f1124aeb0862276 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
 * Copyright (C) 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.android.mobly.snippet.rpc;

import android.content.Intent;
import android.net.Uri;
import com.google.android.mobly.snippet.Snippet;
import com.google.android.mobly.snippet.manager.SnippetManager;
import com.google.android.mobly.snippet.manager.SnippetObjectConverterManager;
import com.google.android.mobly.snippet.util.AndroidUtil;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/** An adapter that wraps {@code Method}. */
public final class MethodDescriptor {
    private final Method mMethod;
    private final Class<? extends Snippet> mClass;

    private MethodDescriptor(Class<? extends Snippet> clazz, Method method) {
        mClass = clazz;
        mMethod = method;
    }

    @Override
    public String toString() {
        return mMethod.getDeclaringClass().getCanonicalName() + "." + mMethod.getName();
    }

    /** Collects all methods with {@code RPC} annotation from given class. */
    public static Collection<MethodDescriptor> collectFrom(Class<? extends Snippet> clazz) {
        List<MethodDescriptor> descriptors = new ArrayList<MethodDescriptor>();
        for (Method method : clazz.getMethods()) {
            if (method.isAnnotationPresent(Rpc.class)
                    || method.isAnnotationPresent(AsyncRpc.class)) {
                descriptors.add(new MethodDescriptor(clazz, method));
            }
        }
        return descriptors;
    }

    /**
     * Invokes the call that belongs to this object with the given parameters. Wraps the response
     * (possibly an exception) in a JSONObject.
     *
     * @param parameters {@code JSONArray} containing the parameters
     * @return result
     * @throws Throwable the exception raised from executing the RPC method.
     */
    public Object invoke(SnippetManager manager, final JSONArray parameters) throws Throwable {
        final Type[] parameterTypes = getGenericParameterTypes();
        final Object[] args = new Object[parameterTypes.length];

        if (parameters.length() > args.length) {
            throw new RpcError("Too many parameters specified.");
        }

        for (int i = 0; i < args.length; i++) {
            final Type parameterType = parameterTypes[i];
            if (i < parameters.length()) {
                args[i] = convertParameter(parameters, i, parameterType);
            } else {
                throw new RpcError("Argument " + (i + 1) + " is not present");
            }
        }

        return manager.invoke(mClass, mMethod, args);
    }

    /** Converts a parameter from JSON into a Java Object. */
    // TODO(damonkohler): This signature is a bit weird (auto-refactored). The obvious alternative
    // would be to work on one supplied parameter and return the converted parameter. However,
    // that's problematic because you lose the ability to call the getXXX methods on the JSON array.
    // @VisibleForTesting
    private static Object convertParameter(final JSONArray parameters, int index, Type type)
            throws JSONException, RpcError {
        try {
            // We must handle null and numbers explicitly because we cannot magically cast them. We
            // also need to convert implicitly from numbers to bools.
            if (parameters.isNull(index)) {
                return null;
            } else if (type == Boolean.class || type == boolean.class) {
                try {
                    return parameters.getBoolean(index);
                } catch (JSONException e) {
                    return parameters.getInt(index) != 0;
                }
            } else if (type == Long.class || type == long.class) {
                return parameters.getLong(index);
            } else if (type == Double.class || type == double.class) {
                return parameters.getDouble(index);
            } else if (type == Integer.class || type == int.class) {
                return parameters.getInt(index);
            } else if (type == Intent.class) {
                return buildIntent(parameters.getJSONObject(index));
            } else if (type == String.class) {
                return parameters.getString(index);
            } else if (type == Integer[].class || type == int[].class) {
                JSONArray list = parameters.getJSONArray(index);
                Integer[] result = new Integer[list.length()];
                for (int i = 0; i < list.length(); i++) {
                    result[i] = list.getInt(i);
                }
                return result;
            } else if (type == Long[].class || type == long[].class) {
                JSONArray list = parameters.getJSONArray(index);
                Long[] result = new Long[list.length()];
                for (int i = 0; i < list.length(); i++) {
                    result[i] = list.getLong(i);
                }
                return result;
            } else if (type == Byte.class || type == byte[].class) {
                JSONArray list = parameters.getJSONArray(index);
                byte[] result = new byte[list.length()];
                for (int i = 0; i < list.length(); i++) {
                    result[i] = (byte) list.getInt(i);
                }
                return result;
            } else if (type == String[].class) {
                JSONArray list = parameters.getJSONArray(index);
                String[] result = new String[list.length()];
                for (int i = 0; i < list.length(); i++) {
                    result[i] = list.getString(i);
                }
                return result;
            } else if (type == JSONObject.class) {
                return parameters.getJSONObject(index);
            } else if (type == JSONArray.class) {
                return parameters.getJSONArray(index);
            } else {
                // Try any custom converter provided.
                Object object =
                        SnippetObjectConverterManager.getInstance()
                                .jsonToObject(parameters.getJSONObject(index), type);
                if (object != null) {
                    return object;
                }
                // Magically cast the parameter to the right Java type.
                return ((Class<?>) type).cast(parameters.get(index));
            }
        } catch (ClassCastException e) {
            throw new RpcError(
                    "Argument "
                            + (index + 1)
                            + " should be of type "
                            + ((Class<?>) type).getSimpleName()
                            + ", but is of type "
                            + parameters.get(index).getClass().getSimpleName());
        }
    }

    private static Object buildIntent(JSONObject jsonObject) throws JSONException {
        Intent intent = new Intent();
        if (jsonObject.has("action")) {
            intent.setAction(jsonObject.getString("action"));
        }
        if (jsonObject.has("data") && jsonObject.has("type")) {
            intent.setDataAndType(
                    Uri.parse(jsonObject.optString("data", null)),
                    jsonObject.optString("type", null));
        } else if (jsonObject.has("data")) {
            intent.setData(Uri.parse(jsonObject.optString("data", null)));
        } else if (jsonObject.has("type")) {
            intent.setType(jsonObject.optString("type", null));
        }
        if (jsonObject.has("packagename") && jsonObject.has("classname")) {
            intent.setClassName(
                    jsonObject.getString("packagename"), jsonObject.getString("classname"));
        }
        if (jsonObject.has("flags")) {
            intent.setFlags(jsonObject.getInt("flags"));
        }
        if (!jsonObject.isNull("extras")) {
            AndroidUtil.putExtrasFromJsonObject(jsonObject.getJSONObject("extras"), intent);
        }
        if (!jsonObject.isNull("categories")) {
            JSONArray categories = jsonObject.getJSONArray("categories");
            for (int i = 0; i < categories.length(); i++) {
                intent.addCategory(categories.getString(i));
            }
        }
        return intent;
    }

    public String getName() {
        return mMethod.getName();
    }

    private Type[] getGenericParameterTypes() {
        return mMethod.getGenericParameterTypes();
    }

    public boolean isAsync() {
        return mMethod.isAnnotationPresent(AsyncRpc.class);
    }

    Class<? extends Snippet> getSnippetClass() {
        return mClass;
    }

    private String getAnnotationDescription() {
        if (isAsync()) {
            AsyncRpc annotation = mMethod.getAnnotation(AsyncRpc.class);
            return annotation.description();
        }
        Rpc annotation = mMethod.getAnnotation(Rpc.class);
        return annotation.description();
    }
    /**
     * Returns a human-readable help text for this RPC, based on annotations in the source code.
     *
     * @return derived help string
     */
    String getHelp() {
        StringBuilder paramBuilder = new StringBuilder();
        Class<?>[] parameterTypes = mMethod.getParameterTypes();
        for (int i = 0; i < parameterTypes.length; i++) {
            if (i != 0) {
                paramBuilder.append(", ");
            }
            paramBuilder.append(parameterTypes[i].getSimpleName());
        }
        return String.format(
                Locale.US,
                "%s %s(%s) returns %s  // %s",
                isAsync() ? "@AsyncRpc" : "@Rpc",
                mMethod.getName(),
                paramBuilder,
                mMethod.getReturnType().getSimpleName(),
                getAnnotationDescription());
    }
}