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

import android.app.AlertDialog;
import android.app.Application;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.EthernetNetworkManagementException;
import android.net.EthernetNetworkSpecifier;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.OutcomeReceiver;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.google.common.base.Strings;

import java.io.IOException;
import java.net.Socket;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public final class MainActivity extends FragmentActivity {
    private static final String TAG = MainActivity.class.getName();
    private static final Duration REQUEST_NETWORK_TIMEOUT =
            Duration.of(200, ChronoUnit.MILLIS);

    private ConfigurationUpdater mConfigurationUpdater;
    private InterfaceEnabler mInterfaceEnabler;
    private CurrentEthernetNetworksViewModel mCurrentEthernetNetworksViewModel;
    private ConnectivityManager mConnectivityManager;

    private final List<Button> mButtons = new ArrayList<>();
    private final List<EditText> mEditTexts = new ArrayList<>();

    private EditText mAllowedPackageNames;
    private EditText mIpConfiguration;
    private EditText mInterfaceName; // used in updateConfiguration
    private EditText mNetworkCapabilities;
    private EditText mInterfaceName2; // used in connect/enable/disable

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAllowedPackageNames = findViewById(R.id.allowedPackageNamesInput);
        mIpConfiguration = findViewById(R.id.ipConfigurationInput);
        mInterfaceName = findViewById(R.id.interfaceNameInput);
        mNetworkCapabilities = findViewById(R.id.networkCapabilitiesInput);
        Button updateButton = findViewById(R.id.updateButton);
        updateButton.setOnClickListener(v -> onUpdateButtonClick());

        mInterfaceName2 = findViewById(R.id.interfaceNameInput2);
        Button connectButton = findViewById(R.id.connectButton);
        connectButton.setOnClickListener(v -> onConnectButtonClick());
        Button enableButton = findViewById(R.id.enableButton);
        enableButton.setOnClickListener(v -> onEnableButtonClick());
        Button disableButton = findViewById(R.id.disableButton);
        disableButton.setOnClickListener(v -> onDisableButtonClick());

        mButtons.add(updateButton);
        mButtons.add(connectButton);
        mButtons.add(enableButton);
        mButtons.add(disableButton);

        mEditTexts.add(mAllowedPackageNames);
        mEditTexts.add(mIpConfiguration);
        mEditTexts.add(mInterfaceName);
        mEditTexts.add(mNetworkCapabilities);
        mEditTexts.add(mInterfaceName2);

        TextView currentEthernetNetworksOutput = findViewById(R.id.currentEthernetNetworksOutput);

        mCurrentEthernetNetworksViewModel =
                new ViewModelProvider(this,
                        new CurrentEthernetNetworksViewModelFactory(
                                (Application) getApplicationContext(),
                                new CurrentEthernetNetworksCallback()))
                        .get(CurrentEthernetNetworksViewModel.class);
        mCurrentEthernetNetworksViewModel.getNetworksLiveData().observe(this,
                networkNetworkInfoMap -> currentEthernetNetworksOutput
                        .setText(mCurrentEthernetNetworksViewModel
                                .getCurrentEthernetNetworksText(networkNetworkInfoMap)));

        OutcomeReceiver<String, EthernetNetworkManagementException> outcomeReceiver =
                new OutcomeReceiver<String, EthernetNetworkManagementException>() {
                    @Override
                    public void onResult(String result) {
                        showOperationResultDialog(result, /* isSuccess= */ true);
                    }

                    @Override
                    public void onError(EthernetNetworkManagementException error) {
                        OutcomeReceiver.super.onError(error);
                        showOperationResultDialog(error.getLocalizedMessage(),
                                /* isSuccess= */ false);
                    }
                };

        mConfigurationUpdater = new ConfigurationUpdater(getApplicationContext(), outcomeReceiver);
        mInterfaceEnabler = new InterfaceEnabler(getApplicationContext(), outcomeReceiver);
        mConnectivityManager = getSystemService(ConnectivityManager.class);
    }

    private void setButtonsAndEditTextsEnabled(boolean isEnabled) {
        for (Button button : mButtons) {
            button.setEnabled(isEnabled);
        }

        for (EditText editText : mEditTexts) {
            editText.setEnabled(isEnabled);
        }
    }

    private void showOperationResultDialog(String message, boolean isSuccess) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(isSuccess ? R.string.success : R.string.error)
                .setMessage(message)
                .setOnDismissListener(d -> setButtonsAndEditTextsEnabled(true))
                .create();
        dialog.show();
    }

    private String getUpdateConfigurationIface() {
        return mInterfaceName.getText().toString();
    }

    private String getEnableDisableConnectIface() {
        return mInterfaceName2.getText().toString();
    }

    private void onUpdateButtonClick() {
        validateInterfaceName(getUpdateConfigurationIface());
        setButtonsAndEditTextsEnabled(false);
        Log.d(TAG, "configuration update started");
        try {
            mConfigurationUpdater.updateNetworkConfiguration(
                    mAllowedPackageNames.getText().toString(),
                    mIpConfiguration.getText().toString(),
                    mNetworkCapabilities.getText().toString(),
                    getUpdateConfigurationIface());
        } catch (IllegalStateException | IllegalArgumentException
                | PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Error updating: " + e.getMessage());
            showOperationResultDialog(e.getLocalizedMessage(), /* isSuccess= */ false);
        }
    }

    private void onConnectButtonClick() {
        setButtonsAndEditTextsEnabled(false);
        Log.d(TAG, "connect interface started");

        try {
            validateInterfaceName(getEnableDisableConnectIface());
            NetworkRequest request =
                    new NetworkRequest.Builder()
                            .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
                            .setNetworkSpecifier(
                            new EthernetNetworkSpecifier(getEnableDisableConnectIface())).build();
            mConnectivityManager.requestNetwork(request,
                    new InterfaceConnectorCallback(),
                    new Handler(Looper.getMainLooper()),
                    Math.toIntExact(REQUEST_NETWORK_TIMEOUT.toMillis()));
        } catch (IllegalArgumentException e) {
            showOperationResultDialog(e.getLocalizedMessage(), /* isSuccess= */ false);
        }
    }

    private void onEnableButtonClick() {
        validateInterfaceName(getEnableDisableConnectIface());
        setButtonsAndEditTextsEnabled(false);
        Log.d(TAG, "enable interface started");
        mInterfaceEnabler.enableInterface(getEnableDisableConnectIface());
    }

    private void onDisableButtonClick() {
        validateInterfaceName(getEnableDisableConnectIface());
        setButtonsAndEditTextsEnabled(false);
        Log.d(TAG, "disable interface started");
        mInterfaceEnabler.disableInterface(getEnableDisableConnectIface());
    }

    private void validateInterfaceName(String iface) {
        if (Strings.isNullOrEmpty(iface)) {
            throw new IllegalArgumentException("Interface Name can't be empty.");
        }
    }

    private class InterfaceConnectorCallback extends ConnectivityManager.NetworkCallback {
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);

            try {
                network.bindSocket(new Socket());
            } catch (IOException e) {
                showOperationResultDialog(e.getLocalizedMessage(), /* isSuccess= */ false);
                return;
            } finally {
                mConnectivityManager.unregisterNetworkCallback(this);
            }

            showOperationResultDialog(
                    mConnectivityManager.getLinkProperties(network).getInterfaceName(),
                    /* isSuccess= */ true);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            mConnectivityManager.unregisterNetworkCallback(this);

            showOperationResultDialog(mInterfaceName2.getText().toString() + " is not available",
                    /* isSuccess= */ false);
        }
    }

    private class CurrentEthernetNetworksCallback extends ConnectivityManager.NetworkCallback {
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            Log.d(TAG, "Network " + network + " available");

            runOnUiThread(() -> mCurrentEthernetNetworksViewModel.addNetwork(network));
        }

        @Override
        public void onLost(Network network) {
            super.onLost(network);
            Log.d(TAG, "Network " + network + " lost");

            runOnUiThread(() -> mCurrentEthernetNetworksViewModel.removeNetwork(network));
        }

        @Override
        public void onCapabilitiesChanged(Network network,
                NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            Log.d(TAG, "Network " + network + " capabilities changed to "
                    + Arrays.toString(networkCapabilities.getCapabilities()));

            runOnUiThread(() -> mCurrentEthernetNetworksViewModel.onNetworkChanged());
        }

        @Override
        public void onLinkPropertiesChanged(Network network,
                LinkProperties linkProperties) {
            super.onLinkPropertiesChanged(network, linkProperties);
            Log.d(TAG, "Network " + network + " link properties changed");

            runOnUiThread(
                    () -> mCurrentEthernetNetworksViewModel.onNetworkChanged());
        }
    }

    private static class CurrentEthernetNetworksViewModelFactory extends
            ViewModelProvider.AndroidViewModelFactory {
        private final Application mApplication;
        private final ConnectivityManager.NetworkCallback mNetworkCallback;

        private CurrentEthernetNetworksViewModelFactory(
                Application application, ConnectivityManager.NetworkCallback networkCallback) {
            super(application);
            mApplication = application;
            mNetworkCallback = networkCallback;
        }

        @NonNull
        @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            return modelClass.cast(
                    new CurrentEthernetNetworksViewModel(mApplication, mNetworkCallback));
        }
    }

}