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