xref: /aosp_15_r20/external/sl4a/Common/src/com/googlecode/android_scripting/jsonrpc/JsonBuilder.java (revision 456ef56af69dcf0481dd36cc45216c4002d72fa3)
1 /*
2  * Copyright (C) 2017 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 com.googlecode.android_scripting.jsonrpc;
18 
19 import static com.googlecode.android_scripting.ConvertUtils.toNonNullString;
20 
21 import android.annotation.NonNull;
22 import android.bluetooth.BluetoothCodecConfig;
23 import android.bluetooth.BluetoothDevice;
24 import android.bluetooth.BluetoothGattCharacteristic;
25 import android.bluetooth.BluetoothGattDescriptor;
26 import android.bluetooth.BluetoothGattService;
27 import android.bluetooth.le.AdvertiseSettings;
28 import android.content.ComponentName;
29 import android.content.Intent;
30 import android.graphics.Point;
31 import android.location.Address;
32 import android.location.Location;
33 import android.media.session.PlaybackState;
34 import android.net.DhcpInfo;
35 import android.net.IpPrefix;
36 import android.net.LinkAddress;
37 import android.net.LinkProperties;
38 import android.net.Network;
39 import android.net.NetworkCapabilities;
40 import android.net.NetworkInfo;
41 import android.net.ProxyInfo;
42 import android.net.RouteInfo;
43 import android.net.Uri;
44 import android.net.wifi.RttManager.RttCapabilities;
45 import android.net.wifi.ScanResult;
46 import android.net.wifi.SoftApCapability;
47 import android.net.wifi.SoftApConfiguration;
48 import android.net.wifi.SoftApInfo;
49 import android.net.wifi.WifiClient;
50 import android.net.wifi.WifiConfiguration;
51 import android.net.wifi.WifiEnterpriseConfig;
52 import android.net.wifi.WifiInfo;
53 import android.net.wifi.WifiScanner;
54 import android.net.wifi.WifiScanner.ScanData;
55 import android.net.wifi.WpsInfo;
56 import android.net.wifi.aware.WifiAwareNetworkInfo;
57 import android.net.wifi.p2p.WifiP2pConfig;
58 import android.net.wifi.p2p.WifiP2pDevice;
59 import android.net.wifi.p2p.WifiP2pGroup;
60 import android.net.wifi.p2p.WifiP2pInfo;
61 import android.os.Bundle;
62 import android.os.ParcelUuid;
63 import android.os.PersistableBundle;
64 import android.os.connectivity.WifiActivityEnergyInfo;
65 import android.telecom.Call;
66 import android.telecom.CallAudioState;
67 import android.telecom.PhoneAccount;
68 import android.telecom.PhoneAccountHandle;
69 import android.telecom.VideoProfile;
70 import android.telecom.VideoProfile.CameraCapabilities;
71 import android.telephony.CellIdentity;
72 import android.telephony.CellIdentityCdma;
73 import android.telephony.CellIdentityGsm;
74 import android.telephony.CellIdentityLte;
75 import android.telephony.CellIdentityTdscdma;
76 import android.telephony.CellIdentityWcdma;
77 import android.telephony.CellIdentityNr;
78 import android.telephony.CellInfo;
79 import android.telephony.CellInfoCdma;
80 import android.telephony.CellInfoGsm;
81 import android.telephony.CellInfoLte;
82 import android.telephony.CellInfoTdscdma;
83 import android.telephony.CellInfoWcdma;
84 import android.telephony.CellInfoNr;
85 import android.telephony.CellLocation;
86 import android.telephony.CellSignalStrengthCdma;
87 import android.telephony.CellSignalStrengthGsm;
88 import android.telephony.CellSignalStrengthLte;
89 import android.telephony.CellSignalStrengthTdscdma;
90 import android.telephony.CellSignalStrengthWcdma;
91 import android.telephony.CellSignalStrengthNr;
92 import android.telephony.ModemActivityInfo;
93 import android.telephony.NeighboringCellInfo;
94 import android.telephony.ServiceState;
95 import android.telephony.SignalStrength;
96 import android.telephony.SmsMessage;
97 import android.telephony.SubscriptionInfo;
98 import android.telephony.VoLteServiceState;
99 import android.telephony.gsm.GsmCellLocation;
100 import android.util.Base64;
101 import android.util.DisplayMetrics;
102 import android.util.SparseArray;
103 import android.util.SparseIntArray;
104 
105 import com.android.internal.net.LegacyVpnInfo;
106 import com.android.modules.utils.build.SdkLevel;
107 
108 import com.googlecode.android_scripting.ConvertUtils;
109 import com.googlecode.android_scripting.Log;
110 import com.googlecode.android_scripting.event.Event;
111 import com.googlecode.android_scripting.facade.ConnectivityConstants;
112 import com.googlecode.android_scripting.facade.DataUsageController.DataUsageInfo;
113 import com.googlecode.android_scripting.facade.telephony.InCallServiceImpl;
114 import com.googlecode.android_scripting.facade.telephony.TelephonyConstants;
115 import com.googlecode.android_scripting.facade.telephony.TelephonyUtils;
116 
117 import org.apache.commons.codec.binary.Base64Codec;
118 import org.json.JSONArray;
119 import org.json.JSONException;
120 import org.json.JSONObject;
121 
122 import java.io.IOException;
123 import java.net.HttpURLConnection;
124 import java.net.InetAddress;
125 import java.net.InetSocketAddress;
126 import java.net.URL;
127 import java.security.PrivateKey;
128 import java.security.cert.CertificateEncodingException;
129 import java.security.cert.X509Certificate;
130 import java.util.ArrayList;
131 import java.util.Collection;
132 import java.util.List;
133 import java.util.Map;
134 import java.util.Map.Entry;
135 import java.util.Set;
136 import java.util.stream.Collectors;
137 import java.util.stream.IntStream;
138 
139 public class JsonBuilder {
140 
141     @SuppressWarnings("unchecked")
build(Object data)142     public static Object build(Object data) throws JSONException {
143         if (data == null) {
144             return JSONObject.NULL;
145         }
146         if (data instanceof Integer) {
147             return data;
148         }
149         if (data instanceof Float) {
150             return data;
151         }
152         if (data instanceof Double) {
153             return data;
154         }
155         if (data instanceof Long) {
156             return data;
157         }
158         if (data instanceof String) {
159             return data;
160         }
161         if (data instanceof Boolean) {
162             return data;
163         }
164         if (data instanceof JsonSerializable) {
165             return ((JsonSerializable) data).toJSON();
166         }
167         if (data instanceof JSONObject) {
168             return data;
169         }
170         if (data instanceof JSONArray) {
171             return data;
172         }
173         if (data instanceof Set<?>) {
174             List<Object> items = new ArrayList<Object>((Set<?>) data);
175             return buildJsonList(items);
176         }
177         if (data instanceof Collection<?>) {
178             List<Object> items = new ArrayList<Object>((Collection<?>) data);
179             return buildJsonList(items);
180         }
181         if (data instanceof List<?>) {
182             return buildJsonList((List<?>) data);
183         }
184         if (data instanceof Address) {
185             return buildJsonAddress((Address) data);
186         }
187         if (data instanceof CallAudioState) {
188             return buildJsonAudioState((CallAudioState) data);
189         }
190         if (data instanceof Location) {
191             return buildJsonLocation((Location) data);
192         }
193         if (data instanceof Bundle) {
194             return buildJsonBundle((Bundle) data);
195         }
196         if (data instanceof Intent) {
197             return buildJsonIntent((Intent) data);
198         }
199         if (data instanceof Event) {
200             return buildJsonEvent((Event) data);
201         }
202         if (data instanceof Map<?, ?>) {
203             // TODO(damonkohler): I would like to make this a checked cast if
204             // possible.
205             return buildJsonMap((Map<String, ?>) data);
206         }
207         if (data instanceof ParcelUuid) {
208             return data.toString();
209         }
210         if (data instanceof ScanResult) {
211             return buildJsonScanResult((ScanResult) data);
212         }
213         if (data instanceof ScanData) {
214             return buildJsonScanData((ScanData) data);
215         }
216         if (data instanceof android.bluetooth.le.ScanResult) {
217             return buildJsonBleScanResult((android.bluetooth.le.ScanResult) data);
218         }
219         if (data instanceof AdvertiseSettings) {
220             return buildJsonBleAdvertiseSettings((AdvertiseSettings) data);
221         }
222         if (data instanceof BluetoothGattService) {
223             return buildJsonBluetoothGattService((BluetoothGattService) data);
224         }
225         if (data instanceof BluetoothGattCharacteristic) {
226             return buildJsonBluetoothGattCharacteristic((BluetoothGattCharacteristic) data);
227         }
228         if (data instanceof BluetoothGattDescriptor) {
229             return buildJsonBluetoothGattDescriptor((BluetoothGattDescriptor) data);
230         }
231         if (data instanceof BluetoothDevice) {
232             return buildJsonBluetoothDevice((BluetoothDevice) data);
233         }
234         if (data instanceof BluetoothCodecConfig) {
235             return buildJsonBluetoothCodecConfig((BluetoothCodecConfig) data);
236         }
237         if (data instanceof PlaybackState) {
238             return buildJsonPlaybackState((PlaybackState) data);
239         }
240         if (data instanceof CellLocation) {
241             return buildJsonCellLocation((CellLocation) data);
242         }
243         if (data instanceof WifiInfo) {
244             return buildJsonWifiInfo((WifiInfo) data);
245         }
246         if (data instanceof NeighboringCellInfo) {
247             return buildNeighboringCellInfo((NeighboringCellInfo) data);
248         }
249         if (data instanceof Network) {
250             return buildNetwork((Network) data);
251         }
252         if (data instanceof NetworkCapabilities) {
253             return buildNetworkCapabilities((NetworkCapabilities) data);
254         }
255         if (data instanceof NetworkInfo) {
256             return buildNetworkInfo((NetworkInfo) data);
257         }
258         if (data instanceof HttpURLConnection) {
259             return buildHttpURLConnection((HttpURLConnection) data);
260         }
261         if (data instanceof InetSocketAddress) {
262             return buildInetSocketAddress((InetSocketAddress) data);
263         }
264         if (data instanceof InetAddress) {
265             return buildInetAddress((InetAddress) data);
266         }
267         if (data instanceof URL) {
268             return buildURL((URL) data);
269         }
270         if (data instanceof Point) {
271             return buildPoint((Point) data);
272         }
273         if (data instanceof SmsMessage) {
274             return buildSmsMessage((SmsMessage) data);
275         }
276         if (data instanceof PhoneAccount) {
277             return buildPhoneAccount((PhoneAccount) data);
278         }
279         if (data instanceof PhoneAccountHandle) {
280             return buildPhoneAccountHandle((PhoneAccountHandle) data);
281         }
282         if (data instanceof SubscriptionInfo) {
283             return buildSubscriptionInfoRecord((SubscriptionInfo) data);
284         }
285         if (data instanceof DataUsageInfo) {
286             return buildDataUsageInfo((DataUsageInfo) data);
287         }
288         if (data instanceof DhcpInfo) {
289             return buildDhcpInfo((DhcpInfo) data);
290         }
291         if (data instanceof DisplayMetrics) {
292             return buildDisplayMetrics((DisplayMetrics) data);
293         }
294         if (data instanceof RttCapabilities) {
295             return buildRttCapabilities((RttCapabilities) data);
296         }
297         if (data instanceof WifiActivityEnergyInfo) {
298             return buildWifiActivityEnergyInfo((WifiActivityEnergyInfo) data);
299         }
300         if (data instanceof SoftApConfiguration) {
301             return buildSoftApConfiguration((SoftApConfiguration) data);
302         }
303         if (data instanceof WifiConfiguration) {
304             return buildWifiConfiguration((WifiConfiguration) data);
305         }
306         if (data instanceof WifiClient) {
307             return buildWifiClient((WifiClient) data);
308         }
309         if (data instanceof WifiP2pConfig) {
310             return buildWifiP2pConfig((WifiP2pConfig) data);
311         }
312         if (data instanceof WifiP2pDevice) {
313             return buildWifiP2pDevice((WifiP2pDevice) data);
314         }
315         if (data instanceof WifiP2pInfo) {
316             return buildWifiP2pInfo((WifiP2pInfo) data);
317         }
318         if (data instanceof WifiP2pGroup) {
319             return buildWifiP2pGroup((WifiP2pGroup) data);
320         }
321         if (data instanceof SoftApCapability) {
322             return buildSoftApCapability((SoftApCapability) data);
323         }
324         if (data instanceof SoftApInfo) {
325             return buildSoftApInfo((SoftApInfo) data);
326         }
327         if (data instanceof LinkProperties) {
328             return buildLinkProperties((LinkProperties) data);
329         }
330         if (data instanceof LinkAddress) {
331             return buildLinkAddress((LinkAddress) data);
332         }
333         if (data instanceof RouteInfo) {
334             return buildRouteInfo((RouteInfo) data);
335         }
336         if (data instanceof IpPrefix) {
337             return buildIpPrefix((IpPrefix) data);
338         }
339         if (data instanceof ProxyInfo) {
340             return buildProxyInfo((ProxyInfo) data);
341         }
342         if (data instanceof byte[]) {
343             JSONArray result = new JSONArray();
344             for (byte b : (byte[]) data) {
345                 result.put(b & 0xFF);
346             }
347             return result;
348         }
349         if (data instanceof Object[]) {
350             return buildJSONArray((Object[]) data);
351         }
352         if (data instanceof CellInfo) {
353             return buildCellInfo((CellInfo) data);
354         }
355         if (data instanceof Call) {
356             return buildCall((Call) data);
357         }
358         if (data instanceof Call.Details) {
359             return buildCallDetails((Call.Details) data);
360         }
361         if (data instanceof InCallServiceImpl.CallEvent<?>) {
362             return buildCallEvent((InCallServiceImpl.CallEvent<?>) data);
363         }
364         if (data instanceof VideoProfile) {
365             return buildVideoProfile((VideoProfile) data);
366         }
367         if (data instanceof CameraCapabilities) {
368             return buildCameraCapabilities((CameraCapabilities) data);
369         }
370         if (data instanceof VoLteServiceState) {
371             return buildVoLteServiceStateEvent((VoLteServiceState) data);
372         }
373         if (data instanceof LegacyVpnInfo) {
374             return buildLegacyVpnInfo((LegacyVpnInfo) data);
375         }
376         if (data instanceof ModemActivityInfo) {
377             return buildModemActivityInfo((ModemActivityInfo) data);
378         }
379         if (data instanceof SignalStrength) {
380             return buildSignalStrength((SignalStrength) data);
381         }
382         if (data instanceof ServiceState) {
383             return buildServiceState((ServiceState) data);
384         }
385         if (data instanceof PersistableBundle) {
386             return buildPersistableBundle((PersistableBundle) data);
387         }
388 
389         return data.toString();
390         // throw new JSONException("Failed to build JSON result. " +
391         // data.getClass().getName());
392     }
393 
buildJsonAudioState(CallAudioState data)394     private static JSONObject buildJsonAudioState(CallAudioState data)
395             throws JSONException {
396         JSONObject state = new JSONObject();
397         state.put("isMuted", data.isMuted());
398         state.put("AudioRoute", InCallServiceImpl.getAudioRouteString(data.getRoute()));
399         return state;
400     }
401 
buildDisplayMetrics(DisplayMetrics data)402     private static Object buildDisplayMetrics(DisplayMetrics data)
403             throws JSONException {
404         JSONObject dm = new JSONObject();
405         dm.put("widthPixels", data.widthPixels);
406         dm.put("heightPixels", data.heightPixels);
407         dm.put("noncompatHeightPixels", data.noncompatHeightPixels);
408         dm.put("noncompatWidthPixels", data.noncompatWidthPixels);
409         return dm;
410     }
411 
buildInetAddress(InetAddress data)412     private static Object buildInetAddress(InetAddress data) {
413         JSONArray address = new JSONArray();
414         address.put(data.getHostName());
415         address.put(data.getHostAddress());
416         return address;
417     }
418 
buildInetSocketAddress(InetSocketAddress data)419     private static Object buildInetSocketAddress(InetSocketAddress data) {
420         JSONArray address = new JSONArray();
421         address.put(data.getHostName());
422         address.put(data.getPort());
423         return address;
424     }
425 
buildJsonAddress(Address address)426     private static JSONObject buildJsonAddress(Address address)
427             throws JSONException {
428         JSONObject result = new JSONObject();
429         result.put("admin_area", address.getAdminArea());
430         result.put("country_code", address.getCountryCode());
431         result.put("country_name", address.getCountryName());
432         result.put("feature_name", address.getFeatureName());
433         result.put("phone", address.getPhone());
434         result.put("locality", address.getLocality());
435         result.put("postal_code", address.getPostalCode());
436         result.put("sub_admin_area", address.getSubAdminArea());
437         result.put("thoroughfare", address.getThoroughfare());
438         result.put("url", address.getUrl());
439         return result;
440     }
441 
buildJSONArray(Object[] data)442     private static JSONArray buildJSONArray(Object[] data) throws JSONException {
443         JSONArray result = new JSONArray();
444         for (Object o : data) {
445             result.put(build(o));
446         }
447         return result;
448     }
449 
buildJsonBleAdvertiseSettings( AdvertiseSettings advertiseSettings)450     private static JSONObject buildJsonBleAdvertiseSettings(
451             AdvertiseSettings advertiseSettings) throws JSONException {
452         JSONObject result = new JSONObject();
453         result.put("mode", advertiseSettings.getMode());
454         result.put("txPowerLevel", advertiseSettings.getTxPowerLevel());
455         result.put("isConnectable", advertiseSettings.isConnectable());
456         return result;
457     }
458 
buildJsonBleScanResult( android.bluetooth.le.ScanResult scanResult)459     private static JSONObject buildJsonBleScanResult(
460             android.bluetooth.le.ScanResult scanResult) throws JSONException {
461         JSONObject result = new JSONObject();
462         result.put("rssi", scanResult.getRssi());
463         result.put("timestampNanos", scanResult.getTimestampNanos());
464         result.put("deviceName", scanResult.getScanRecord().getDeviceName());
465         result.put("txPowerLevel", scanResult.getScanRecord().getTxPowerLevel());
466         result.put("advertiseFlags", scanResult.getScanRecord()
467                 .getAdvertiseFlags());
468         ArrayList<String> manufacturerDataList = new ArrayList<String>();
469         ArrayList<Integer> idList = new ArrayList<Integer>();
470         if (scanResult.getScanRecord().getManufacturerSpecificData() != null) {
471             SparseArray<byte[]> manufacturerSpecificData = scanResult
472                     .getScanRecord().getManufacturerSpecificData();
473             for (int i = 0; i < manufacturerSpecificData.size(); i++) {
474                 manufacturerDataList.add(ConvertUtils
475                         .convertByteArrayToString(manufacturerSpecificData
476                                 .valueAt(i)));
477                 idList.add(manufacturerSpecificData.keyAt(i));
478             }
479         }
480         result.put("manufacturerSpecificDataList", manufacturerDataList);
481         result.put("manufacturerIdList", idList);
482         ArrayList<String> serviceUuidList = new ArrayList<String>();
483         ArrayList<String> serviceDataList = new ArrayList<String>();
484         if (scanResult.getScanRecord().getServiceData() != null) {
485             Map<ParcelUuid, byte[]> serviceDataMap = scanResult.getScanRecord()
486                     .getServiceData();
487             for (ParcelUuid serviceUuid : serviceDataMap.keySet()) {
488                 serviceUuidList.add(serviceUuid.toString());
489                 serviceDataList.add(ConvertUtils
490                         .convertByteArrayToString(serviceDataMap
491                                 .get(serviceUuid)));
492             }
493         }
494         result.put("serviceUuidList", serviceUuidList);
495         result.put("serviceDataList", serviceDataList);
496         List<ParcelUuid> serviceUuids = scanResult.getScanRecord()
497                 .getServiceUuids();
498         String serviceUuidsString = "";
499         if (serviceUuids != null && serviceUuids.size() > 0) {
500             for (ParcelUuid uuid : serviceUuids) {
501                 serviceUuidsString = serviceUuidsString + "," + uuid;
502             }
503         }
504         result.put("serviceUuids", serviceUuidsString);
505         result.put("scanRecord",
506                 build(ConvertUtils.convertByteArrayToString(scanResult
507                         .getScanRecord().getBytes())));
508         result.put("deviceInfo", build(scanResult.getDevice()));
509         return result;
510     }
511 
buildJsonBluetoothCodecConfig(BluetoothCodecConfig codecConfig)512     private static JSONObject buildJsonBluetoothCodecConfig(BluetoothCodecConfig codecConfig)
513             throws JSONException {
514         JSONObject result = new JSONObject();
515         result.put("codecType", codecConfig.getCodecType());
516         result.put("sampleRate", codecConfig.getSampleRate());
517         result.put("bitsPerSample", codecConfig.getBitsPerSample());
518         result.put("channelMode", codecConfig.getChannelMode());
519         result.put("codecSpecific1", codecConfig.getCodecSpecific1());
520         return result;
521     }
522 
buildJsonBluetoothDevice(BluetoothDevice data)523     private static JSONObject buildJsonBluetoothDevice(BluetoothDevice data)
524             throws JSONException {
525         JSONObject deviceInfo = new JSONObject();
526         deviceInfo.put("address", data.getAddress());
527         deviceInfo.put("state", data.getBondState());
528         deviceInfo.put("name", data.getName());
529         deviceInfo.put("type", data.getType());
530         return deviceInfo;
531     }
532 
buildJsonBluetoothGattCharacteristic( BluetoothGattCharacteristic data)533     private static Object buildJsonBluetoothGattCharacteristic(
534             BluetoothGattCharacteristic data) throws JSONException {
535         JSONObject result = new JSONObject();
536         result.put("instanceId", data.getInstanceId());
537         result.put("permissions", data.getPermissions());
538         result.put("properties", data.getProperties());
539         result.put("writeType", data.getWriteType());
540         result.put("descriptorsList", build(data.getDescriptors()));
541         result.put("uuid", data.getUuid().toString());
542         result.put("value", build(data.getValue()));
543 
544         return result;
545     }
546 
buildJsonBluetoothGattDescriptor( BluetoothGattDescriptor data)547     private static Object buildJsonBluetoothGattDescriptor(
548             BluetoothGattDescriptor data) throws JSONException {
549         JSONObject result = new JSONObject();
550         result.put("instanceId", data.getInstanceId());
551         result.put("permissions", data.getPermissions());
552         result.put("characteristic", data.getCharacteristic());
553         result.put("uuid", data.getUuid().toString());
554         result.put("value", build(data.getValue()));
555         return result;
556     }
557 
buildJsonBluetoothGattService( BluetoothGattService data)558     private static Object buildJsonBluetoothGattService(
559             BluetoothGattService data) throws JSONException {
560         JSONObject result = new JSONObject();
561         result.put("instanceId", data.getInstanceId());
562         result.put("type", data.getType());
563         result.put("gattCharacteristicList", build(data.getCharacteristics()));
564         result.put("includedServices", build(data.getIncludedServices()));
565         result.put("uuid", data.getUuid().toString());
566         return result;
567     }
568 
buildJsonBundle(Bundle bundle)569     private static JSONObject buildJsonBundle(Bundle bundle)
570             throws JSONException {
571         JSONObject result = new JSONObject();
572         for (String key : bundle.keySet()) {
573             result.put(key, build(bundle.get(key)));
574         }
575         return result;
576     }
577 
buildJsonCellLocation(CellLocation cellLocation)578     private static JSONObject buildJsonCellLocation(CellLocation cellLocation)
579             throws JSONException {
580         JSONObject result = new JSONObject();
581         if (cellLocation instanceof GsmCellLocation) {
582             GsmCellLocation location = (GsmCellLocation) cellLocation;
583             result.put("lac", location.getLac());
584             result.put("cid", location.getCid());
585         }
586         // TODO(damonkohler): Add support for CdmaCellLocation. Not supported
587         // until API level 5.
588         return result;
589     }
590 
buildDhcpInfo(DhcpInfo data)591     private static JSONObject buildDhcpInfo(DhcpInfo data) throws JSONException {
592         JSONObject result = new JSONObject();
593         result.put("ipAddress", data.ipAddress);
594         result.put("dns1", data.dns1);
595         result.put("dns2", data.dns2);
596         result.put("gateway", data.gateway);
597         result.put("serverAddress", data.serverAddress);
598         result.put("leaseDuration", data.leaseDuration);
599         return result;
600     }
601 
buildJsonEvent(Event event)602     private static JSONObject buildJsonEvent(Event event) throws JSONException {
603         JSONObject result = new JSONObject();
604         result.put("name", event.getName());
605         result.put("data", build(event.getData()));
606         result.put("time", event.getCreationTime());
607         return result;
608     }
609 
buildJsonIntent(Intent data)610     private static JSONObject buildJsonIntent(Intent data) throws JSONException {
611         JSONObject result = new JSONObject();
612         result.put("data", data.getDataString());
613         result.put("type", data.getType());
614         result.put("extras", build(data.getExtras()));
615         result.put("categories", build(data.getCategories()));
616         result.put("action", data.getAction());
617         ComponentName component = data.getComponent();
618         if (component != null) {
619             result.put("packagename", component.getPackageName());
620             result.put("classname", component.getClassName());
621         }
622         result.put("flags", data.getFlags());
623         return result;
624     }
625 
buildJsonList(final List<T> list)626     private static <T> JSONArray buildJsonList(final List<T> list)
627             throws JSONException {
628         JSONArray result = new JSONArray();
629         for (T item : list) {
630             result.put(build(item));
631         }
632         return result;
633     }
634 
buildJsonLocation(Location location)635     private static JSONObject buildJsonLocation(Location location)
636             throws JSONException {
637         JSONObject result = new JSONObject();
638         result.put("altitude", location.getAltitude());
639         result.put("latitude", location.getLatitude());
640         result.put("longitude", location.getLongitude());
641         result.put("time", location.getTime());
642         result.put("accuracy", location.getAccuracy());
643         result.put("speed", location.getSpeed());
644         result.put("provider", location.getProvider());
645         result.put("bearing", location.getBearing());
646         return result;
647     }
648 
buildJsonMap(Map<String, ?> map)649     private static JSONObject buildJsonMap(Map<String, ?> map)
650             throws JSONException {
651         JSONObject result = new JSONObject();
652         for (Entry<String, ?> entry : map.entrySet()) {
653             String key = entry.getKey();
654             if (key == null) {
655                 key = "";
656             }
657             result.put(key, build(entry.getValue()));
658         }
659         return result;
660     }
661 
buildJsonPlaybackState(PlaybackState playbackState)662     private static JSONObject buildJsonPlaybackState(PlaybackState playbackState)
663             throws JSONException {
664         JSONObject result = new JSONObject();
665         result.put("state", playbackState.getState());
666         result.put("position", playbackState.getPosition());
667         result.put("speed", playbackState.getPlaybackSpeed());
668         result.put("actions", playbackState.getActions());
669         return result;
670     }
671 
buildJsonScanResult(ScanResult scanResult)672     private static JSONObject buildJsonScanResult(ScanResult scanResult)
673             throws JSONException {
674         JSONObject result = new JSONObject();
675         result.put("BSSID", scanResult.BSSID);
676         result.put("SSID", scanResult.SSID);
677         result.put("frequency", scanResult.frequency);
678         result.put("level", scanResult.level);
679         result.put("capabilities", scanResult.capabilities);
680         result.put("timestamp", scanResult.timestamp);
681         result.put("centerFreq0", scanResult.centerFreq0);
682         result.put("centerFreq1", scanResult.centerFreq1);
683         result.put("channelWidth", scanResult.channelWidth);
684         result.put("distanceCm", scanResult.distanceCm);
685         result.put("distanceSdCm", scanResult.distanceSdCm);
686         result.put("is80211McRTTResponder", scanResult.is80211mcResponder());
687         result.put("passpointNetwork", scanResult.isPasspointNetwork());
688         result.put("numUsage", scanResult.numUsage);
689         result.put("seen", scanResult.seen);
690         result.put("untrusted", scanResult.untrusted);
691         result.put("operatorFriendlyName", scanResult.operatorFriendlyName);
692         result.put("venueName", scanResult.venueName);
693         if (scanResult.informationElements != null) {
694             JSONArray infoEles = new JSONArray();
695             for (ScanResult.InformationElement ie : scanResult.informationElements) {
696                 JSONObject infoEle = new JSONObject();
697                 infoEle.put("id", ie.id);
698                 infoEle.put("bytes", Base64Codec.encodeBase64String(ie.bytes));
699                 infoEles.put(infoEle);
700             }
701             result.put("InformationElements", infoEles);
702         } else {
703             result.put("InformationElements", null);
704         }
705         if (scanResult.radioChainInfos != null) {
706             JSONArray radioChainEles = new JSONArray();
707             for (ScanResult.RadioChainInfo item : scanResult.radioChainInfos) {
708                 JSONObject radioChainEle = new JSONObject();
709                 radioChainEle.put("id", item.id);
710                 radioChainEle.put("level", item.level);
711                 radioChainEles.put(radioChainEle);
712             }
713             result.put("radioChainInfos", radioChainEles);
714         } else {
715             result.put("radioChainInfos", null);
716         }
717         return result;
718     }
719 
buildJsonScanData(ScanData scanData)720     private static JSONObject buildJsonScanData(ScanData scanData)
721             throws JSONException {
722         JSONObject result = new JSONObject();
723         result.put("Id", scanData.getId());
724         result.put("Flags", scanData.getFlags());
725         JSONArray scanResults = new JSONArray();
726         for (ScanResult sr : scanData.getResults()) {
727             scanResults.put(buildJsonScanResult(sr));
728         }
729         result.put("ScanResults", scanResults);
730         return result;
731     }
732 
buildJsonWifiInfo(WifiInfo data)733     private static JSONObject buildJsonWifiInfo(WifiInfo data)
734             throws JSONException {
735         JSONObject result = new JSONObject();
736         result.put("hidden_ssid", data.getHiddenSSID());
737         result.put("ip_address", data.getIpAddress());
738         result.put("link_speed", data.getLinkSpeed());
739         result.put("network_id", data.getNetworkId());
740         result.put("rssi", data.getRssi());
741         result.put("BSSID", data.getBSSID());
742         result.put("mac_address", data.getMacAddress());
743         result.put("frequency", data.getFrequency());
744         // Trim the double quotes if exist
745         String ssid = data.getSSID();
746         if (ssid.charAt(0) == '"'
747                 && ssid.charAt(ssid.length() - 1) == '"') {
748             result.put("SSID", ssid.substring(1, ssid.length() - 1));
749         } else {
750             result.put("SSID", ssid);
751         }
752         String supplicantState = "";
753         switch (data.getSupplicantState()) {
754             case ASSOCIATED:
755                 supplicantState = "associated";
756                 break;
757             case ASSOCIATING:
758                 supplicantState = "associating";
759                 break;
760             case COMPLETED:
761                 supplicantState = "completed";
762                 break;
763             case DISCONNECTED:
764                 supplicantState = "disconnected";
765                 break;
766             case DORMANT:
767                 supplicantState = "dormant";
768                 break;
769             case FOUR_WAY_HANDSHAKE:
770                 supplicantState = "four_way_handshake";
771                 break;
772             case GROUP_HANDSHAKE:
773                 supplicantState = "group_handshake";
774                 break;
775             case INACTIVE:
776                 supplicantState = "inactive";
777                 break;
778             case INVALID:
779                 supplicantState = "invalid";
780                 break;
781             case SCANNING:
782                 supplicantState = "scanning";
783                 break;
784             case UNINITIALIZED:
785                 supplicantState = "uninitialized";
786                 break;
787             default:
788                 supplicantState = null;
789         }
790         result.put("supplicant_state", build(supplicantState));
791         result.put("is_5ghz", data.is5GHz());
792         result.put("is_6ghz", data.is6GHz());
793         result.put("is_24ghz", data.is24GHz());
794         return result;
795     }
796 
buildNeighboringCellInfo(NeighboringCellInfo data)797     private static JSONObject buildNeighboringCellInfo(NeighboringCellInfo data)
798             throws JSONException {
799         JSONObject result = new JSONObject();
800         result.put("cid", data.getCid());
801         result.put("rssi", data.getRssi());
802         result.put("lac", data.getLac());
803         result.put("psc", data.getPsc());
804         String networkType = TelephonyUtils.getNetworkTypeString(data.getNetworkType());
805         result.put("network_type", build(networkType));
806         return result;
807     }
808 
buildCellInfo(CellInfo data)809     private static JSONObject buildCellInfo(CellInfo data) throws JSONException {
810         JSONObject result = new JSONObject();
811         result.put("registered", data.isRegistered());
812         result.put("connection_status", data.getCellConnectionStatus());
813         result.put("timestamp", data.getTimeStamp());
814 
815         CellIdentity cid = data.getCellIdentity();
816         result.put("channel_number", cid.getChannelNumber());
817         result.put("alpha_long", cid.getOperatorAlphaLong());
818         result.put("alpha_short", cid.getOperatorAlphaShort());
819 
820         if (data instanceof CellInfoLte) {
821             return buildCellInfoLte((CellInfoLte) data, result);
822         } else if (data instanceof CellInfoNr) {
823             return buildCellInfoNr((CellInfoNr) data, result);
824         } else if (data instanceof CellInfoWcdma) {
825             return buildCellInfoWcdma((CellInfoWcdma) data, result);
826         } else if (data instanceof CellInfoTdscdma) {
827             return buildCellInfoTdscdma((CellInfoTdscdma) data, result);
828         } else if (data instanceof CellInfoGsm) {
829             return buildCellInfoGsm((CellInfoGsm) data, result);
830         } else if (data instanceof CellInfoCdma) {
831             return buildCellInfoCdma((CellInfoCdma) data, result);
832         }
833         return result;
834     }
835 
buildCellInfoLte(CellInfoLte data, JSONObject result)836     private static JSONObject buildCellInfoLte(CellInfoLte data, JSONObject result)
837             throws JSONException {
838         result.put("rat", "lte");
839         CellIdentityLte cellidentity = data.getCellIdentity();
840         CellSignalStrengthLte signalstrength = data.getCellSignalStrength();
841         result.put("mcc", cellidentity.getMcc());
842         result.put("mnc", cellidentity.getMnc());
843         result.put("mcc_string", cellidentity.getMccString());
844         result.put("mnc_string", cellidentity.getMncString());
845         result.put("cid", cellidentity.getCi());
846         result.put("pcid", cellidentity.getPci());
847         result.put("tac", cellidentity.getTac());
848         result.put("bandwidth", cellidentity.getBandwidth());
849         result.put("rsrp", signalstrength.getDbm());
850         result.put("asulevel", signalstrength.getAsuLevel());
851         result.put("timing_advance", signalstrength.getTimingAdvance());
852         return result;
853     }
854 
buildCellInfoNr(CellInfoNr data, JSONObject result)855     private static JSONObject buildCellInfoNr(CellInfoNr data, JSONObject result)
856             throws JSONException {
857         result.put("rat", "nr");
858         CellIdentityNr cellidentity = (CellIdentityNr)data.getCellIdentity();
859         CellSignalStrengthNr signalstrength = (CellSignalStrengthNr)data.getCellSignalStrength();
860         result.put("mcc_string", cellidentity.getMccString());
861         result.put("mnc_string", cellidentity.getMncString());
862         result.put("band", cellidentity.getBands());
863         result.put("arfcn", cellidentity.getNrarfcn());
864         result.put("cid", cellidentity.getNci());
865         result.put("pcid", cellidentity.getPci());
866         result.put("tac", cellidentity.getTac());
867         result.put("rsrp", signalstrength.getDbm());
868         result.put("asulevel", signalstrength.getAsuLevel());
869         return result;
870     }
871 
buildCellInfoGsm(CellInfoGsm data, JSONObject result)872     private static JSONObject buildCellInfoGsm(CellInfoGsm data, JSONObject result)
873             throws JSONException {
874         result.put("rat", "gsm");
875         CellIdentityGsm cellidentity = data.getCellIdentity();
876         CellSignalStrengthGsm signalstrength = data.getCellSignalStrength();
877         result.put("mcc", cellidentity.getMcc());
878         result.put("mnc", cellidentity.getMnc());
879         result.put("mcc_string", cellidentity.getMccString());
880         result.put("mnc_string", cellidentity.getMncString());
881         result.put("cid", cellidentity.getCid());
882         result.put("lac", cellidentity.getLac());
883         result.put("bsic", cellidentity.getBsic());
884         result.put("arfcn", cellidentity.getArfcn());
885         result.put("signal_strength", signalstrength.getDbm());
886         result.put("asulevel", signalstrength.getAsuLevel());
887         return result;
888     }
889 
buildCellInfoWcdma(CellInfoWcdma data, JSONObject result)890     private static JSONObject buildCellInfoWcdma(CellInfoWcdma data, JSONObject result)
891             throws JSONException {
892         result.put("rat", "wcdma");
893         CellIdentityWcdma cellidentity = data.getCellIdentity();
894         CellSignalStrengthWcdma signalstrength = data.getCellSignalStrength();
895         result.put("mcc", cellidentity.getMcc());
896         result.put("mnc", cellidentity.getMnc());
897         result.put("mcc_string", cellidentity.getMccString());
898         result.put("mnc_string", cellidentity.getMncString());
899         result.put("cid", cellidentity.getCid());
900         result.put("lac", cellidentity.getLac());
901         result.put("psc", cellidentity.getPsc());
902         result.put("signal_strength", signalstrength.getDbm());
903         result.put("asulevel", signalstrength.getAsuLevel());
904         return result;
905     }
906 
buildCellInfoTdscdma(CellInfoTdscdma data, JSONObject result)907     private static JSONObject buildCellInfoTdscdma(CellInfoTdscdma data, JSONObject result)
908             throws JSONException {
909         result.put("rat", "tdscdma");
910         CellIdentityTdscdma cellidentity = data.getCellIdentity();
911         CellSignalStrengthTdscdma signalstrength = data.getCellSignalStrength();
912         result.put("mcc_string", cellidentity.getMccString());
913         result.put("mnc_string", cellidentity.getMncString());
914         result.put("cid", cellidentity.getCid());
915         result.put("lac", cellidentity.getLac());
916         result.put("cpid", cellidentity.getCpid());
917         result.put("signal_strength", signalstrength.getDbm());
918         result.put("asulevel", signalstrength.getAsuLevel());
919         return result;
920     }
921 
buildCellInfoCdma(CellInfoCdma data, JSONObject result)922     private static JSONObject buildCellInfoCdma(CellInfoCdma data, JSONObject result)
923             throws JSONException {
924         result.put("rat", "cdma");
925         result.put("registered", data.isRegistered());
926         CellIdentityCdma cellidentity = data.getCellIdentity();
927         CellSignalStrengthCdma signalstrength = data.getCellSignalStrength();
928         result.put("network_id", cellidentity.getNetworkId());
929         result.put("system_id", cellidentity.getSystemId());
930         result.put("basestation_id", cellidentity.getBasestationId());
931         result.put("longitude", cellidentity.getLongitude());
932         result.put("latitude", cellidentity.getLatitude());
933         result.put("cdma_dbm", signalstrength.getCdmaDbm());
934         result.put("cdma_ecio", signalstrength.getCdmaEcio());
935         result.put("evdo_dbm", signalstrength.getEvdoDbm());
936         result.put("evdo_ecio", signalstrength.getEvdoEcio());
937         result.put("evdo_snr", signalstrength.getEvdoSnr());
938         return result;
939     }
940 
buildHttpURLConnection(HttpURLConnection data)941     private static Object buildHttpURLConnection(HttpURLConnection data)
942             throws JSONException {
943         JSONObject con = new JSONObject();
944         try {
945             con.put("ResponseCode", data.getResponseCode());
946             con.put("ResponseMessage", data.getResponseMessage());
947         } catch (IOException e) {
948             e.printStackTrace();
949             return con;
950         }
951         con.put("ContentLength", data.getContentLength());
952         con.put("ContentEncoding", data.getContentEncoding());
953         con.put("ContentType", data.getContentType());
954         con.put("Date", data.getDate());
955         con.put("ReadTimeout", data.getReadTimeout());
956         con.put("HeaderFields", buildJsonMap(data.getHeaderFields()));
957         con.put("URL", buildURL(data.getURL()));
958         return con;
959     }
960 
buildNetwork(Network data)961     private static Object buildNetwork(Network data) throws JSONException {
962         JSONObject nw = new JSONObject();
963         nw.put("netId", data.getNetId());
964         return nw;
965     }
966 
buildNetworkCapabilities(JSONObject nc, NetworkCapabilities data)967     public static JSONObject buildNetworkCapabilities(JSONObject nc, NetworkCapabilities data)
968             throws JSONException {
969         nc.put(ConnectivityConstants.NetworkCallbackContainer.RSSI,
970                 data.getSignalStrength());
971         nc.put(ConnectivityConstants.NetworkCallbackContainer.METERED,
972                 !data.hasCapability(ConnectivityConstants.NET_CAPABILITY_TEMPORARILY_NOT_METERED));
973         nc.put(ConnectivityConstants.NET_CAPABILITIES_TRANSPORT_TYPE,
974                 new JSONArray(data.getTransportTypes()));
975         nc.put(ConnectivityConstants.NET_CAPABILITIES_CAPABILITIES,
976                 new JSONArray(data.getCapabilities()));
977 
978         if (data.getNetworkSpecifier() != null) {
979             nc.put("network_specifier",
980                     data.getNetworkSpecifier().toString());
981         }
982         if (data.getTransportInfo() != null) {
983             nc.put("transport_info",
984                     JsonBuilder.build(data.getTransportInfo()));
985             if (data.getTransportInfo() instanceof WifiAwareNetworkInfo) {
986                 WifiAwareNetworkInfo anc =
987                         (WifiAwareNetworkInfo) data.getTransportInfo();
988 
989                 String ipv6 = anc.getPeerIpv6Addr().toString();
990                 if (ipv6.charAt(0) == '/') {
991                     ipv6 = ipv6.substring(1);
992                 }
993                 nc.put("aware_ipv6", ipv6);
994                 if (anc.getPort() != 0) {
995                     nc.put("aware_port", anc.getPort());
996                 }
997                 if (anc.getTransportProtocol() != -1) {
998                     nc.put("aware_transport_protocol", anc.getTransportProtocol());
999                 }
1000             }
1001         }
1002         return nc;
1003     }
1004 
buildNetworkCapabilities(NetworkCapabilities data)1005     private static Object buildNetworkCapabilities(NetworkCapabilities data) throws JSONException {
1006         return buildNetworkCapabilities(new JSONObject(), data);
1007     }
1008 
buildNetworkInfo(NetworkInfo data)1009     private static Object buildNetworkInfo(NetworkInfo data)
1010             throws JSONException {
1011         JSONObject info = new JSONObject();
1012         info.put("isAvailable", data.isAvailable());
1013         info.put("isConnected", data.isConnected());
1014         info.put("isFailover", data.isFailover());
1015         info.put("isRoaming", data.isRoaming());
1016         info.put("ExtraInfo", data.getExtraInfo());
1017         info.put("FailedReason", data.getReason());
1018         info.put("TypeName", data.getTypeName());
1019         info.put("SubtypeName", data.getSubtypeName());
1020         info.put("State", data.getState().name().toString());
1021         return info;
1022     }
1023 
buildURL(URL data)1024     private static Object buildURL(URL data) throws JSONException {
1025         JSONObject url = new JSONObject();
1026         url.put("Authority", data.getAuthority());
1027         url.put("Host", data.getHost());
1028         url.put("Path", data.getPath());
1029         url.put("Port", data.getPort());
1030         url.put("Protocol", data.getProtocol());
1031         return url;
1032     }
1033 
1034     /**
1035      * Builds a json representation of a {@link DataUsageInfo}.
1036      * @param data The DataUsageInfo convert to JSON.
1037      * @return A JSONObject representation of a {@link DataUsageInfo}.
1038      * @throws JSONException
1039      */
buildDataUsageInfo(@onNull DataUsageInfo data)1040     private static JSONObject buildDataUsageInfo(@NonNull DataUsageInfo data)
1041             throws JSONException {
1042         JSONObject usage = new JSONObject();
1043         usage.put("SubscriberId", data.subscriberId);
1044         usage.put("Period", data.period);
1045         usage.put("StartEpochMilli", data.startEpochMilli);
1046         usage.put("EndEpochMilli", data.endEpochMilli);
1047         usage.put("CycleStart", data.cycleStart);
1048         usage.put("CycleEnd", data.cycleEnd);
1049         usage.put("LimitLevel", data.limitLevel);
1050         usage.put("WarningLevel", data.warningLevel);
1051         usage.put("UsageLevel", data.usageLevel);
1052         usage.put("Uid", data.uId);
1053         return usage;
1054     }
1055 
1056     /**
1057      * Builds a json representation of a {@link PhoneAccount}.
1058      * @param data The PhoneAccount convert to JSON.
1059      * @return A JSONObject representation of a {@link PhoneAccount}.
1060      * @throws JSONException
1061      */
buildPhoneAccount(@onNull PhoneAccount data)1062     private static JSONObject buildPhoneAccount(@NonNull PhoneAccount data)
1063             throws JSONException {
1064         JSONObject acct = new JSONObject();
1065         acct.put("Address", toNonNullString(data.getAddress(), Uri::toSafeString));
1066         acct.put("SubscriptionAddress", toNonNullString(data.getSubscriptionAddress(),
1067                 Uri::toSafeString));
1068         acct.put("Label", toNonNullString(data.getLabel()));
1069         acct.put("ShortDescription", toNonNullString(data.getShortDescription()));
1070         return acct;
1071     }
1072 
buildPhoneAccountHandle(PhoneAccountHandle data)1073     private static Object buildPhoneAccountHandle(PhoneAccountHandle data)
1074             throws JSONException {
1075         JSONObject msg = new JSONObject();
1076         msg.put("id", data.getId());
1077         msg.put("ComponentName", data.getComponentName().flattenToString());
1078         return msg;
1079     }
1080 
buildSubscriptionInfoRecord(SubscriptionInfo data)1081     private static Object buildSubscriptionInfoRecord(SubscriptionInfo data)
1082             throws JSONException {
1083         JSONObject msg = new JSONObject();
1084         msg.put("subscriptionId", data.getSubscriptionId());
1085         msg.put("iccId", data.getIccId());
1086         msg.put("simSlotIndex", data.getSimSlotIndex());
1087         msg.put("displayName", data.getDisplayName());
1088         msg.put("nameSource", data.getDisplayNameSource());
1089         msg.put("iconTint", data.getIconTint());
1090         msg.put("number", data.getNumber());
1091         msg.put("dataRoaming", data.getDataRoaming());
1092         msg.put("mcc", data.getMcc());
1093         msg.put("mnc", data.getMnc());
1094         msg.put("carrierId", data.getCarrierId());
1095         msg.put("isOpportunistic", data.isOpportunistic());
1096         return msg;
1097     }
1098 
buildPoint(Point data)1099     private static Object buildPoint(Point data) throws JSONException {
1100         JSONObject point = new JSONObject();
1101         point.put("x", data.x);
1102         point.put("y", data.y);
1103         return point;
1104     }
1105 
buildRttCapabilities(RttCapabilities data)1106     private static Object buildRttCapabilities(RttCapabilities data)
1107             throws JSONException {
1108         JSONObject cap = new JSONObject();
1109         cap.put("bwSupported", data.bwSupported);
1110         cap.put("lciSupported", data.lciSupported);
1111         cap.put("lcrSupported", data.lcrSupported);
1112         cap.put("oneSidedRttSupported", data.oneSidedRttSupported);
1113         cap.put("preambleSupported", data.preambleSupported);
1114         cap.put("twoSided11McRttSupported", data.twoSided11McRttSupported);
1115         return cap;
1116     }
1117 
buildSmsMessage(SmsMessage data)1118     private static Object buildSmsMessage(SmsMessage data) throws JSONException {
1119         JSONObject msg = new JSONObject();
1120         msg.put("originatingAddress", data.getOriginatingAddress());
1121         msg.put("messageBody", data.getMessageBody());
1122         return msg;
1123     }
1124 
buildWifiActivityEnergyInfo( WifiActivityEnergyInfo data)1125     private static JSONObject buildWifiActivityEnergyInfo(
1126             WifiActivityEnergyInfo data) throws JSONException {
1127         JSONObject result = new JSONObject();
1128         result.put("ControllerEnergyUsed", data.getControllerEnergyUsedMicroJoules());
1129         result.put("ControllerIdleTimeMillis", data.getControllerIdleDurationMillis());
1130         result.put("ControllerRxTimeMillis", data.getControllerRxDurationMillis());
1131         result.put("ControllerTxTimeMillis", data.getControllerTxDurationMillis());
1132         result.put("StackState", data.getStackState());
1133         result.put("TimeStamp", data.getTimeSinceBootMillis());
1134         return result;
1135     }
1136 
apBand2wifiScannerBand( @oftApConfiguration.BandType int band)1137     private static @WifiScanner.WifiBand int apBand2wifiScannerBand(
1138             @SoftApConfiguration.BandType int band) {
1139         switch(band) {
1140             case SoftApConfiguration.BAND_2GHZ:
1141                 return WifiScanner.WIFI_BAND_24_GHZ;
1142             case SoftApConfiguration.BAND_5GHZ:
1143                 return WifiScanner.WIFI_BAND_5_GHZ;
1144             case SoftApConfiguration.BAND_6GHZ:
1145                 return WifiScanner.WIFI_BAND_6_GHZ;
1146             case SoftApConfiguration.BAND_60GHZ:
1147                 return WifiScanner.WIFI_BAND_60_GHZ;
1148             default:
1149                 return WifiScanner.WIFI_BAND_UNSPECIFIED;
1150         }
1151     }
1152 
buildSoftApConfiguration(SoftApConfiguration data)1153     private static Object buildSoftApConfiguration(SoftApConfiguration data)
1154             throws JSONException {
1155         JSONObject config = new JSONObject();
1156         config.put("SSID", data.getSsid());
1157         config.put("BSSID", data.getBssid());
1158         config.put("hiddenSSID", data.isHiddenSsid());
1159         int securityType = data.getSecurityType();
1160         if (securityType == SoftApConfiguration.SECURITY_TYPE_OPEN) {
1161             config.put("security", "NONE");
1162         } else if (securityType == SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) {
1163             config.put("security", "WPA2_PSK");
1164         } else if (securityType == SoftApConfiguration.SECURITY_TYPE_WPA3_SAE_TRANSITION) {
1165             config.put("security", "WPA3_SAE_TRANSITION");
1166         } else if (securityType == SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) {
1167             config.put("security", "WPA3_SAE");
1168         }
1169         if (data.getPassphrase() != null) {
1170             config.put("password", data.getPassphrase());
1171         }
1172         config.put("apBand", data.getBand());
1173         config.put("apChannel", data.getChannel());
1174         config.put("MaxNumberOfClients", data.getMaxNumberOfClients());
1175         config.put("ShutdownTimeoutMillis", data.getShutdownTimeoutMillis());
1176         config.put("AutoShutdownEnabled", data.isAutoShutdownEnabled());
1177         config.put("ClientControlByUserEnabled", data.isClientControlByUserEnabled());
1178         config.put("AllowedClientList", build(data.getAllowedClientList()));
1179         config.put("BlockedClientList", build(data.getBlockedClientList()));
1180         if (SdkLevel.isAtLeastS()) {
1181             config.put("apBands", buildJSONArray(
1182                     IntStream.of(data.getBands()).boxed().toArray(Integer[]::new)));
1183             SparseIntArray channels = data.getChannels();
1184             int[] channelFrequencies = new int[channels.size()];
1185             for (int i = 0; i < channels.size(); i++) {
1186                 int channel = channels.valueAt(i);
1187                 channelFrequencies[i] = channel == 0 ? 0
1188                         : ScanResult.convertChannelToFrequencyMhzIfSupported(
1189                         channel, apBand2wifiScannerBand(channels.keyAt(i)));
1190             }
1191             if (channelFrequencies.length != 0) {
1192                 config.put("apChannelFrequencies", build(
1193                         IntStream.of(channelFrequencies).boxed().toArray(Integer[]::new)));
1194             }
1195             config.put("MacRandomizationSetting", build(data.getMacRandomizationSetting()));
1196             config.put("BridgedModeOpportunisticShutdownEnabled",
1197                     build(data.isBridgedModeOpportunisticShutdownEnabled()));
1198             config.put("Ieee80211axEnabled", build(data.isIeee80211axEnabled()));
1199         }
1200         return config;
1201     }
1202 
buildWifiClient(WifiClient data)1203     private static Object buildWifiClient(WifiClient data) throws JSONException {
1204         JSONObject config = new JSONObject();
1205         config.put("MacAddress", data.getMacAddress().toString());
1206         return config;
1207     }
1208 
buildWifiConfiguration(WifiConfiguration data)1209     private static Object buildWifiConfiguration(WifiConfiguration data)
1210             throws JSONException {
1211         JSONObject config = new JSONObject();
1212         config.put("networkId", data.networkId);
1213         // Trim the double quotes if exist
1214         if (data.SSID.charAt(0) == '"'
1215                 && data.SSID.charAt(data.SSID.length() - 1) == '"') {
1216             config.put("SSID", data.SSID.substring(1, data.SSID.length() - 1));
1217         } else {
1218             config.put("SSID", data.SSID);
1219         }
1220         config.put("BSSID", data.BSSID);
1221         config.put("priority", data.priority);
1222         config.put("hiddenSSID", data.hiddenSSID);
1223         config.put("FQDN", data.FQDN);
1224         config.put("providerFriendlyName", data.providerFriendlyName);
1225         config.put("isPasspoint", data.isPasspoint());
1226         config.put("hiddenSSID", data.hiddenSSID);
1227         config.put("carrierId", data.carrierId);
1228         if (data.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SAE)) {
1229             config.put("security", "SAE");
1230         } else if (data.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
1231             config.put("security", "PSK");
1232         } else if (data.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.OWE)) {
1233             config.put("security", "OWE");
1234         } else if (data.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SUITE_B_192)) {
1235             config.put("security", "SUITE_B_192");
1236         } else if (data.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) {
1237             config.put("security", "EAP");
1238         } else if (data.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
1239             config.put("security", "NONE");
1240         }
1241         if (data.status == WifiConfiguration.Status.CURRENT) {
1242             config.put("status", "CURRENT");
1243         } else if (data.status == WifiConfiguration.Status.DISABLED) {
1244             config.put("status", "DISABLED");
1245         } else if (data.status == WifiConfiguration.Status.ENABLED) {
1246             config.put("status", "ENABLED");
1247         } else {
1248             config.put("status", "UNKNOWN");
1249         }
1250         // config.put("enterpriseConfig", buildWifiEnterpriseConfig(data.enterpriseConfig));
1251         return config;
1252     }
1253 
buildWifiEnterpriseConfig(WifiEnterpriseConfig data)1254     private static Object buildWifiEnterpriseConfig(WifiEnterpriseConfig data)
1255             throws JSONException, CertificateEncodingException {
1256         JSONObject config = new JSONObject();
1257         config.put(WifiEnterpriseConfig.PLMN_KEY, data.getPlmn());
1258         config.put(WifiEnterpriseConfig.REALM_KEY, data.getRealm());
1259         config.put(WifiEnterpriseConfig.EAP_KEY, data.getEapMethod());
1260         config.put(WifiEnterpriseConfig.PHASE2_KEY, data.getPhase2Method());
1261         config.put(WifiEnterpriseConfig.ALTSUBJECT_MATCH_KEY, data.getAltSubjectMatch());
1262         X509Certificate caCert = data.getCaCertificate();
1263         String caCertString = Base64.encodeToString(caCert.getEncoded(), Base64.DEFAULT);
1264         config.put(WifiEnterpriseConfig.CA_CERT_KEY, caCertString);
1265         X509Certificate clientCert = data.getClientCertificate();
1266         String clientCertString = Base64.encodeToString(clientCert.getEncoded(), Base64.DEFAULT);
1267         config.put(WifiEnterpriseConfig.CLIENT_CERT_KEY, clientCertString);
1268         PrivateKey pk = data.getClientPrivateKey();
1269         String privateKeyString = Base64.encodeToString(pk.getEncoded(), Base64.DEFAULT);
1270         config.put(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, privateKeyString);
1271         config.put(WifiEnterpriseConfig.PASSWORD_KEY, data.getPassword());
1272         config.put(WifiEnterpriseConfig.OCSP, data.getOcsp());
1273         return config;
1274     }
1275 
buildWpsInfo(WpsInfo data)1276     private static JSONObject buildWpsInfo(WpsInfo data)
1277             throws JSONException {
1278         JSONObject wpsInfo = new JSONObject();
1279         wpsInfo.put("setup", data.setup);
1280         wpsInfo.put("BSSID", data.BSSID);
1281         wpsInfo.put("pin", data.pin);
1282         return wpsInfo;
1283     }
1284 
buildWifiP2pConfig(WifiP2pConfig data)1285     private static JSONObject buildWifiP2pConfig(WifiP2pConfig data)
1286             throws JSONException {
1287         JSONObject wifiP2pConfig = new JSONObject();
1288         wifiP2pConfig.put("deviceAddress", data.deviceAddress);
1289         wifiP2pConfig.put("wpsInfo", buildWpsInfo(data.wps));
1290         wifiP2pConfig.put("groupOwnerIntent", data.groupOwnerIntent);
1291         wifiP2pConfig.put("netId", data.netId);
1292         return wifiP2pConfig;
1293     }
1294 
buildWifiP2pDevice(WifiP2pDevice data)1295     private static JSONObject buildWifiP2pDevice(WifiP2pDevice data)
1296             throws JSONException {
1297         JSONObject deviceInfo = new JSONObject();
1298         deviceInfo.put("Name", data.deviceName);
1299         deviceInfo.put("Address", data.deviceAddress);
1300         deviceInfo.put("GroupCapability", data.groupCapability);
1301         return deviceInfo;
1302     }
1303 
buildWifiP2pGroup(WifiP2pGroup data)1304     private static JSONObject buildWifiP2pGroup(WifiP2pGroup data)
1305             throws JSONException {
1306         JSONObject group = new JSONObject();
1307         Log.d("build p2p group.");
1308         group.put("ClientList", build(data.getClientList()));
1309         group.put("Interface", data.getInterface());
1310         group.put("Networkname", data.getNetworkName());
1311         group.put("Owner", data.getOwner());
1312         group.put("Passphrase", data.getPassphrase());
1313         group.put("NetworkId", data.getNetworkId());
1314         return group;
1315     }
1316 
buildWifiP2pInfo(WifiP2pInfo data)1317     private static JSONObject buildWifiP2pInfo(WifiP2pInfo data)
1318             throws JSONException {
1319         JSONObject info = new JSONObject();
1320         Log.d("build p2p info.");
1321         info.put("groupFormed", data.groupFormed);
1322         info.put("isGroupOwner", data.isGroupOwner);
1323         info.put("groupOwnerAddress", data.groupOwnerAddress);
1324         return info;
1325     }
1326 
buildSoftApCapability(SoftApCapability data)1327     private static JSONObject buildSoftApCapability(SoftApCapability data)
1328             throws JSONException {
1329         JSONObject info = new JSONObject();
1330         Log.d("build softAp capability info.");
1331         info.put("maxSupportedClients", data.getMaxSupportedClients());
1332         info.put("acsOffloadSupported", data.areFeaturesSupported(
1333                 SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD));
1334         info.put("clientForceDisconnectSupported", data.areFeaturesSupported(
1335                 SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT));
1336         info.put("wpa3SaeSupported", data.areFeaturesSupported(
1337                 SoftApCapability.SOFTAP_FEATURE_WPA3_SAE));
1338         info.put("ieee80211axSupported", data.areFeaturesSupported(
1339                 SoftApCapability.SOFTAP_FEATURE_IEEE80211_AX));
1340         info.put("24gSupported", data.areFeaturesSupported(
1341                 SoftApCapability.SOFTAP_FEATURE_BAND_24G_SUPPORTED));
1342         info.put("5gSupported", data.areFeaturesSupported(
1343                 SoftApCapability.SOFTAP_FEATURE_BAND_5G_SUPPORTED));
1344         info.put("6gSupported", data.areFeaturesSupported(
1345                 SoftApCapability.SOFTAP_FEATURE_BAND_6G_SUPPORTED));
1346         info.put("60gSupported", data.areFeaturesSupported(
1347                 SoftApCapability.SOFTAP_FEATURE_BAND_60G_SUPPORTED));
1348         info.put("supported2GHzChannellist", build(
1349                 IntStream.of(data.getSupportedChannelList(SoftApConfiguration.BAND_2GHZ))
1350                 .boxed().toArray(Integer[]::new)));
1351 
1352         info.put("supported5GHzChannellist", build(
1353                 IntStream.of(data.getSupportedChannelList(SoftApConfiguration.BAND_5GHZ))
1354                 .boxed().toArray(Integer[]::new)));
1355         info.put("supported6GHzChannellist", build(
1356                 IntStream.of(data.getSupportedChannelList(SoftApConfiguration.BAND_6GHZ))
1357                 .boxed().toArray(Integer[]::new)));
1358         info.put("supported60GHzChannellist", build(
1359                 IntStream.of(data.getSupportedChannelList(SoftApConfiguration.BAND_60GHZ))
1360                 .boxed().toArray(Integer[]::new)));
1361         return info;
1362     }
1363 
buildSoftApInfo(SoftApInfo data)1364     private static JSONObject buildSoftApInfo(SoftApInfo data)
1365             throws JSONException {
1366         JSONObject info = new JSONObject();
1367         Log.d("build softAp info.");
1368         info.put("frequency", data.getFrequency());
1369         info.put("bandwidth", data.getBandwidth());
1370         info.put("autoShutdownTimeoutMillis", data.getAutoShutdownTimeoutMillis());
1371         if (SdkLevel.isAtLeastS()) {
1372             info.put("wifiStandard", data.getWifiStandard());
1373             info.put("bssid", data.getBssid());
1374         }
1375         return info;
1376     }
1377 
buildLinkProperties(LinkProperties data)1378     private static JSONObject buildLinkProperties(LinkProperties data) throws JSONException {
1379         JSONObject info = new JSONObject();
1380         info.put("InterfaceName", data.getInterfaceName());
1381         info.put("LinkAddresses", build(data.getLinkAddresses()));
1382         info.put("DnsServers", build(data.getDnsServers()));
1383         info.put("Domains", data.getDomains());
1384         info.put("Mtu", data.getMtu());
1385         info.put("Routes", build(data.getRoutes()));
1386         info.put("IsPrivateDnsActive", data.isPrivateDnsActive());
1387         info.put("PrivateDnsServerName", data.getPrivateDnsServerName());
1388         info.put("ValidatedPrivateDnsServers", build(data.getValidatedPrivateDnsServers()));
1389         return info;
1390     }
1391 
buildLinkAddress(LinkAddress data)1392     private static JSONObject buildLinkAddress(LinkAddress data) throws JSONException {
1393         JSONObject info = new JSONObject();
1394         info.put("Address", build(data.getAddress()));
1395         info.put("PrefixLength", data.getPrefixLength());
1396         info.put("Scope", data.getScope());
1397         info.put("Flags", data.getFlags());
1398         return info;
1399     }
1400 
buildRouteInfo(RouteInfo data)1401     private static JSONObject buildRouteInfo(RouteInfo data) throws JSONException {
1402         JSONObject info = new JSONObject();
1403         info.put("Destination", build(data.getDestination()));
1404         info.put("Gateway", build(data.getGateway()));
1405         info.put("Interface", data.getInterface());
1406         info.put("IsDefaultRoute", data.isDefaultRoute());
1407         return info;
1408     }
1409 
buildIpPrefix(IpPrefix data)1410     private static JSONObject buildIpPrefix(IpPrefix data) throws JSONException {
1411         JSONObject info = new JSONObject();
1412         info.put("Address", data.getAddress());
1413         info.put("PrefixLength", data.getPrefixLength());
1414         return info;
1415     }
1416 
buildProxyInfo(ProxyInfo data)1417     private static JSONObject buildProxyInfo(ProxyInfo data) throws JSONException {
1418         JSONObject info = new JSONObject();
1419         info.put("Hostname", data.getHost());
1420         info.put("Port", data.getPort());
1421         info.put("ExclList", data.getExclusionListAsString());
1422         info.put("PacUrl", data.getPacFileUrl().toString());
1423         return info;
1424     }
1425 
buildCallEvent(InCallServiceImpl.CallEvent<T> callEvent)1426     private static <T> JSONObject buildCallEvent(InCallServiceImpl.CallEvent<T> callEvent)
1427             throws JSONException {
1428         JSONObject jsonEvent = new JSONObject();
1429         jsonEvent.put("CallId", callEvent.getCallId());
1430         jsonEvent.put("Event", build(callEvent.getEvent()));
1431         return jsonEvent;
1432     }
1433 
buildUri(Uri uri)1434     private static JSONObject buildUri(Uri uri) throws JSONException {
1435         return new JSONObject().put("Uri", build((uri != null) ? uri.toString() : ""));
1436     }
1437 
buildCallDetails(Call.Details details)1438     private static JSONObject buildCallDetails(Call.Details details) throws JSONException {
1439 
1440         JSONObject callDetails = new JSONObject();
1441 
1442         callDetails.put("Handle", buildUri(details.getHandle()));
1443         callDetails.put("HandlePresentation",
1444                 build(InCallServiceImpl.getCallPresentationInfoString(
1445                         details.getHandlePresentation())));
1446         callDetails.put("CallerDisplayName", build(details.getCallerDisplayName()));
1447 
1448         // TODO AccountHandle
1449         // callDetails.put("AccountHandle", build(""));
1450 
1451         callDetails.put("Capabilities",
1452                 build(InCallServiceImpl.getCallCapabilitiesString(details.getCallCapabilities())));
1453 
1454         callDetails.put("Properties",
1455                 build(InCallServiceImpl.getCallPropertiesString(details.getCallProperties())));
1456 
1457         // TODO Parse fields in Disconnect Cause
1458         callDetails.put("DisconnectCause", build((details.getDisconnectCause() != null) ? details
1459                 .getDisconnectCause().toString() : ""));
1460         callDetails.put("ConnectTimeMillis", build(details.getConnectTimeMillis()));
1461 
1462         // TODO: GatewayInfo
1463         // callDetails.put("GatewayInfo", build(""));
1464 
1465         callDetails.put("VideoState",
1466                 build(InCallServiceImpl.getVideoCallStateString(details.getVideoState())));
1467 
1468         // TODO: StatusHints
1469         // callDetails.put("StatusHints", build(""));
1470 
1471         callDetails.put("Extras", build(details.getExtras()));
1472 
1473         return callDetails;
1474     }
1475 
buildCall(Call call)1476     private static JSONObject buildCall(Call call) throws JSONException {
1477 
1478         JSONObject callInfo = new JSONObject();
1479 
1480         callInfo.put("Parent", build(InCallServiceImpl.getCallId(call)));
1481 
1482         // TODO:Make a function out of this for consistency
1483         ArrayList<String> children = new ArrayList<String>();
1484         for (Call child : call.getChildren()) {
1485             children.add(InCallServiceImpl.getCallId(child));
1486         }
1487         callInfo.put("Children", build(children));
1488 
1489         // TODO:Make a function out of this for consistency
1490         ArrayList<String> conferenceables = new ArrayList<String>();
1491         for (Call conferenceable : call.getChildren()) {
1492             children.add(InCallServiceImpl.getCallId(conferenceable));
1493         }
1494         callInfo.put("ConferenceableCalls", build(conferenceables));
1495 
1496         callInfo.put("State", build(InCallServiceImpl.getCallStateString(call.getState())));
1497         callInfo.put("CannedTextResponses", build(call.getCannedTextResponses()));
1498         callInfo.put("VideoCall", InCallServiceImpl.getVideoCallId(call.getVideoCall()));
1499         callInfo.put("Details", build(call.getDetails()));
1500 
1501         return callInfo;
1502     }
1503 
buildVideoProfile(VideoProfile videoProfile)1504     private static JSONObject buildVideoProfile(VideoProfile videoProfile) throws JSONException {
1505         JSONObject profile = new JSONObject();
1506 
1507         profile.put("VideoState",
1508                 InCallServiceImpl.getVideoCallStateString(videoProfile.getVideoState()));
1509         profile.put("VideoQuality",
1510                 InCallServiceImpl.getVideoCallQualityString(videoProfile.getQuality()));
1511 
1512         return profile;
1513     }
1514 
buildCameraCapabilities(CameraCapabilities cameraCapabilities)1515     private static JSONObject buildCameraCapabilities(CameraCapabilities cameraCapabilities)
1516             throws JSONException {
1517         JSONObject capabilities = new JSONObject();
1518 
1519         capabilities.put("Height", build(cameraCapabilities.getHeight()));
1520         capabilities.put("Width", build(cameraCapabilities.getWidth()));
1521         capabilities.put("ZoomSupported", build(cameraCapabilities.isZoomSupported()));
1522         capabilities.put("MaxZoom", build(cameraCapabilities.getMaxZoom()));
1523 
1524         return capabilities;
1525     }
1526 
buildVoLteServiceStateEvent( VoLteServiceState volteInfo)1527     private static JSONObject buildVoLteServiceStateEvent(
1528             VoLteServiceState volteInfo)
1529             throws JSONException {
1530         JSONObject info = new JSONObject();
1531         info.put(TelephonyConstants.VoLteServiceStateContainer.SRVCC_STATE,
1532                 TelephonyUtils.getSrvccStateString(volteInfo.getSrvccState()));
1533         return info;
1534     }
1535 
buildLegacyVpnInfo(LegacyVpnInfo data)1536     private static JSONObject buildLegacyVpnInfo(LegacyVpnInfo data) throws JSONException {
1537         JSONObject info = new JSONObject();
1538         if (data == null) {
1539             return info;
1540         }
1541         info.put("state", data.state);
1542         info.put("key", data.key);
1543         String intentStr = "";
1544         if (data.intent != null) {
1545             intentStr = data.intent.toString();
1546         }
1547         info.put("intent", intentStr);
1548         return info;
1549     }
1550 
buildModemActivityInfo(ModemActivityInfo modemInfo)1551     private static JSONObject buildModemActivityInfo(ModemActivityInfo modemInfo)
1552             throws JSONException {
1553         JSONObject info = new JSONObject();
1554 
1555         info.put("Timestamp", modemInfo.getTimestampMillis());
1556         info.put("SleepTimeMs", modemInfo.getSleepTimeMillis());
1557         info.put("IdleTimeMs", modemInfo.getIdleTimeMillis());
1558         List<Long> txPowerDurations = IntStream.range(0, 5)
1559                 .mapToLong(modemInfo::getTransmitDurationMillisAtPowerLevel)
1560                 .boxed()
1561                 .collect(Collectors.toList());
1562         info.put("TxTimeMs", build(txPowerDurations));
1563         info.put("RxTimeMs", modemInfo.getReceiveTimeMillis());
1564         return info;
1565     }
1566 
buildPersistableBundle( PersistableBundle bundle)1567     private static JSONObject buildPersistableBundle(
1568             PersistableBundle bundle) throws JSONException {
1569         JSONObject result = new JSONObject();
1570         for (String key : bundle.keySet()) {
1571             result.put(key, build(bundle.get(key)));
1572         }
1573         return result;
1574     }
1575 
buildSignalStrength(SignalStrength signalStrength)1576     private static JSONObject buildSignalStrength(SignalStrength signalStrength)
1577             throws JSONException {
1578         JSONObject info = new JSONObject();
1579         info.put(TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_GSM,
1580                 signalStrength.getGsmSignalStrength());
1581         info.put(
1582                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_GSM_DBM,
1583                 signalStrength.getGsmDbm());
1584         info.put(
1585                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_GSM_LEVEL,
1586                 signalStrength.getGsmLevel());
1587         info.put(
1588                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_GSM_ASU_LEVEL,
1589                 signalStrength.getGsmAsuLevel());
1590         info.put(
1591                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_GSM_BIT_ERROR_RATE,
1592                 signalStrength.getGsmBitErrorRate());
1593         info.put(
1594                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_CDMA_DBM,
1595                 signalStrength.getCdmaDbm());
1596         info.put(
1597                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_CDMA_LEVEL,
1598                 signalStrength.getCdmaLevel());
1599         info.put(
1600                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_CDMA_ASU_LEVEL,
1601                 signalStrength.getCdmaAsuLevel());
1602         info.put(
1603                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_CDMA_ECIO,
1604                 signalStrength.getCdmaEcio());
1605         info.put(
1606                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_EVDO_DBM,
1607                 signalStrength.getEvdoDbm());
1608         info.put(
1609                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_EVDO_ECIO,
1610                 signalStrength.getEvdoEcio());
1611         info.put(TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_LTE,
1612                 signalStrength.getLteSignalStrength());
1613         info.put(
1614                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_LTE_DBM,
1615                 signalStrength.getLteDbm());
1616         info.put(
1617                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_LTE_LEVEL,
1618                 signalStrength.getLteLevel());
1619         info.put(
1620                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_LTE_ASU_LEVEL,
1621                 signalStrength.getLteAsuLevel());
1622         info.put(
1623                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_LEVEL,
1624                 signalStrength.getLevel());
1625         info.put(
1626                 TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_ASU_LEVEL,
1627                 signalStrength.getAsuLevel());
1628         info.put(TelephonyConstants.SignalStrengthContainer.SIGNAL_STRENGTH_DBM,
1629                 signalStrength.getDbm());
1630         return info;
1631     }
1632 
buildServiceState(ServiceState ss)1633     public static JSONObject buildServiceState(ServiceState ss) throws JSONException {
1634         JSONObject info = new JSONObject();
1635 
1636         info.put(TelephonyConstants.ServiceStateContainer.VOICE_REG_STATE,
1637                 TelephonyUtils.getNetworkStateString(ss.getState()));
1638         info.put(TelephonyConstants.ServiceStateContainer.VOICE_NETWORK_TYPE,
1639                 TelephonyUtils.getNetworkTypeString(ss.getVoiceNetworkType()));
1640         info.put(TelephonyConstants.ServiceStateContainer.DATA_REG_STATE,
1641                 TelephonyUtils.getNetworkStateString(ss.getDataRegistrationState()));
1642         info.put(TelephonyConstants.ServiceStateContainer.DATA_NETWORK_TYPE,
1643                 TelephonyUtils.getNetworkTypeString(ss.getDataNetworkType()));
1644         info.put(TelephonyConstants.ServiceStateContainer.OPERATOR_NAME, ss.getOperatorAlphaLong());
1645         info.put(TelephonyConstants.ServiceStateContainer.OPERATOR_ID, ss.getOperatorNumeric());
1646         info.put(TelephonyConstants.ServiceStateContainer.IS_MANUAL_NW_SELECTION,
1647                 ss.getIsManualSelection());
1648         info.put(TelephonyConstants.ServiceStateContainer.ROAMING, ss.getRoaming());
1649         info.put(TelephonyConstants.ServiceStateContainer.IS_EMERGENCY_ONLY, ss.isEmergencyOnly());
1650         info.put(TelephonyConstants.ServiceStateContainer.NETWORK_ID, ss.getCdmaNetworkId());
1651         info.put(TelephonyConstants.ServiceStateContainer.SYSTEM_ID, ss.getCdmaSystemId());
1652         info.put(TelephonyConstants.ServiceStateContainer.SERVICE_STATE,
1653                 TelephonyUtils.getNetworkStateString(ss.getState()));
1654         info.put(TelephonyConstants.ServiceStateContainer.CHANNEL_NUMBER, ss.getChannelNumber());
1655         info.put(TelephonyConstants.ServiceStateContainer.CELL_BANDWIDTHS,
1656                 ss.getCellBandwidths() != null
1657                         ? new JSONArray(ss.getCellBandwidths())
1658                         : JSONObject.NULL);
1659         info.put(TelephonyConstants.ServiceStateContainer.DUPLEX_MODE, ss.getDuplexMode());
1660         info.put(TelephonyConstants.ServiceStateContainer.VOICE_ROAMING_TYPE,
1661                 ss.getVoiceRoamingType());
1662         info.put(TelephonyConstants.ServiceStateContainer.DATA_ROAMING_TYPE,
1663                 ss.getDataRoamingType());
1664         info.put(TelephonyConstants.ServiceStateContainer.VOICE_OPERATOR_ALPHA_LONG,
1665                 ss.getOperatorAlphaLong());
1666         info.put(TelephonyConstants.ServiceStateContainer.VOICE_OPERATOR_ALPHA_SHORT,
1667                 ss.getOperatorAlphaShort());
1668         info.put(TelephonyConstants.ServiceStateContainer.VOICE_OPERATOR_NUMERIC,
1669                 ss.getOperatorNumeric());
1670         info.put(TelephonyConstants.ServiceStateContainer.DATA_OPERATOR_ALPHA_LONG,
1671                 ss.getOperatorAlphaLong());
1672         info.put(TelephonyConstants.ServiceStateContainer.DATA_OPERATOR_ALPHA_SHORT,
1673                 ss.getOperatorAlphaShort());
1674         info.put(TelephonyConstants.ServiceStateContainer.DATA_OPERATOR_NUMERIC,
1675                 ss.getOperatorNumeric());
1676         info.put(TelephonyConstants.ServiceStateContainer.VOICE_RADIO_TECHNOLOGY,
1677                 ss.getRilVoiceRadioTechnology());
1678         info.put(TelephonyConstants.ServiceStateContainer.DATA_RADIO_TECHNOLOGY,
1679                 ss.getRilDataRadioTechnology());
1680         info.put(TelephonyConstants.ServiceStateContainer.CSS_INDICATOR, ss.getCssIndicator());
1681         info.put(TelephonyConstants.ServiceStateContainer.CDMA_ROAMING_INDICATOR,
1682                 ss.getCdmaRoamingIndicator());
1683         info.put(TelephonyConstants.ServiceStateContainer.CDMA_DEFAULT_ROAMING_INDICATOR,
1684                 ss.getCdmaDefaultRoamingIndicator());
1685         info.put(TelephonyConstants.ServiceStateContainer.IS_DATA_ROAMING_FROM_REGISTRATION,
1686                 ss.getDataRoamingFromRegistration());
1687         info.put(TelephonyConstants.ServiceStateContainer.IS_USING_CARRIER_AGGREGATION,
1688                 ss.isUsingCarrierAggregation());
1689         info.put(TelephonyConstants.ServiceStateContainer.LTE_EARFCN_RSRP_BOOST,
1690                 ss.getArfcnRsrpBoost());
1691         return info;
1692     }
1693 
JsonBuilder()1694     private JsonBuilder() {
1695         // This is a utility class.
1696     }
1697 }
1698