diff options
author | Samuel Holland <samuel@sholland.org> | 2018-04-30 11:37:52 -0500 |
---|---|---|
committer | Samuel Holland <samuel@sholland.org> | 2018-04-30 11:50:21 -0500 |
commit | 843003f436846d6bfe0b7832d391043cca3579f2 (patch) | |
tree | 0d3cc9033ff3a0b7613adbd48f591f345f1b13a9 /app/src/main/java | |
parent | 8e4fb91a28c01b753a72a8a9130e7b4d78e9ee83 (diff) |
global: Clean up Java
Address Java and Android lints.
Signed-off-by: Samuel Holland <samuel@sholland.org>
Diffstat (limited to 'app/src/main/java')
13 files changed, 237 insertions, 215 deletions
diff --git a/app/src/main/java/com/wireguard/android/activity/BaseActivity.java b/app/src/main/java/com/wireguard/android/activity/BaseActivity.java index eb2de5ed..6ee9ff14 100644 --- a/app/src/main/java/com/wireguard/android/activity/BaseActivity.java +++ b/app/src/main/java/com/wireguard/android/activity/BaseActivity.java @@ -49,7 +49,7 @@ public abstract class BaseActivity extends AppCompatActivity { super.onCreate(savedInstanceState); if (Application.getComponent().getBackendType() == GoBackend.class) { - Intent intent = GoBackend.VpnService.prepare(this); + final Intent intent = GoBackend.VpnService.prepare(this); if (intent != null) { startActivityForResult(intent, 0); } diff --git a/app/src/main/java/com/wireguard/android/activity/MainActivity.java b/app/src/main/java/com/wireguard/android/activity/MainActivity.java index bfb3be7e..307d0bf6 100644 --- a/app/src/main/java/com/wireguard/android/activity/MainActivity.java +++ b/app/src/main/java/com/wireguard/android/activity/MainActivity.java @@ -68,7 +68,7 @@ public class MainActivity extends BaseActivity { fragment = ((TunnelListFragment) getSupportFragmentManager().getFragments().get(0)); - } catch (ClassCastException ignored) { + } catch (final ClassCastException ignored) { } if (fragment == null || !(fragment.collapseActionMenu())) { if (!moveToState(State.ofLayer(state.layer - 1))) diff --git a/app/src/main/java/com/wireguard/android/activity/SettingsActivity.java b/app/src/main/java/com/wireguard/android/activity/SettingsActivity.java index fb5e7a09..46a90daa 100644 --- a/app/src/main/java/com/wireguard/android/activity/SettingsActivity.java +++ b/app/src/main/java/com/wireguard/android/activity/SettingsActivity.java @@ -17,28 +17,29 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Interface for changing application-global persistent settings. */ public class SettingsActivity extends AppCompatActivity { - private HashMap<Integer, PermissionRequestCallback> permissionRequestCallbacks = new HashMap<>(); - private int permissionRequestCounter = 0; + private final Map<Integer, PermissionRequestCallback> permissionRequestCallbacks = new HashMap<>(); + private int permissionRequestCounter; - public synchronized void ensurePermissions(String[] permissions, PermissionRequestCallback cb) { - List<String> needPermissions = new ArrayList<>(permissions.length); + public void ensurePermissions(final String[] permissions, final PermissionRequestCallback cb) { + final List<String> needPermissions = new ArrayList<>(permissions.length); for (final String permission : permissions) { if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) needPermissions.add(permission); } if (needPermissions.isEmpty()) { - int[] granted = new int[permissions.length]; + final int[] granted = new int[permissions.length]; Arrays.fill(granted, PackageManager.PERMISSION_GRANTED); cb.done(permissions, granted); return; } - int idx = permissionRequestCounter++; + final int idx = permissionRequestCounter++; permissionRequestCallbacks.put(idx, cb); ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), idx); } @@ -54,7 +55,7 @@ public class SettingsActivity extends AppCompatActivity { } @Override - public boolean onOptionsItemSelected(MenuItem item) { + public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); @@ -65,7 +66,7 @@ public class SettingsActivity extends AppCompatActivity { } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { final PermissionRequestCallback f = permissionRequestCallbacks.get(requestCode); if (f != null) { permissionRequestCallbacks.remove(requestCode); @@ -73,7 +74,6 @@ public class SettingsActivity extends AppCompatActivity { } } - @FunctionalInterface public interface PermissionRequestCallback { void done(String[] permissions, int[] grantResults); } diff --git a/app/src/main/java/com/wireguard/android/backend/GoBackend.java b/app/src/main/java/com/wireguard/android/backend/GoBackend.java index 519f7427..e055c353 100644 --- a/app/src/main/java/com/wireguard/android/backend/GoBackend.java +++ b/app/src/main/java/com/wireguard/android/backend/GoBackend.java @@ -33,11 +33,11 @@ public final class GoBackend implements Backend { System.loadLibrary("wg-go"); } - private Context context; + private final Context context; private Tunnel currentTunnel; private int currentTunnelHandle = -1; - public GoBackend(Context context) { + public GoBackend(final Context context) { this.context = context; } @@ -108,14 +108,14 @@ public final class GoBackend implements Backend { if (VpnService.prepare(context) != null) throw new Exception("VPN service not authorized by user"); - VpnService service; + final VpnService service; if (!vpnService.isDone()) startVpnService(); try { service = vpnService.get(2, TimeUnit.SECONDS); - } catch (TimeoutException e) { - throw new Exception("Unable to start Android VPN service"); + } catch (final TimeoutException e) { + throw new Exception("Unable to start Android VPN service", e); } if (currentTunnelHandle != -1) { @@ -124,29 +124,32 @@ public final class GoBackend implements Backend { } // Build config - Formatter fmt = new Formatter(new StringBuilder()); final Interface iface = config.getInterface(); - fmt.format("replace_peers=true\n"); - if (iface.getPrivateKey() != null) - fmt.format("private_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(iface.getPrivateKey()))); - if (iface.getListenPort() != 0) - fmt.format("listen_port=%d\n", config.getInterface().getListenPort()); - for (final Peer peer : config.getPeers()) { - if (peer.getPublicKey() != null) - fmt.format("public_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPublicKey()))); - if (peer.getPreSharedKey() != null) - fmt.format("preshared_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPreSharedKey()))); - if (peer.getEndpoint() != null) - fmt.format("endpoint=%s\n", peer.getResolvedEndpointString()); - if (peer.getPersistentKeepalive() != 0) - fmt.format("persistent_keepalive_interval=%d\n", peer.getPersistentKeepalive()); - for (final IPCidr addr : peer.getAllowedIPs()) { - fmt.format("allowed_ip=%s\n", addr.toString()); + final String goConfig; + try (Formatter fmt = new Formatter(new StringBuilder())) { + fmt.format("replace_peers=true\n"); + if (iface.getPrivateKey() != null) + fmt.format("private_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(iface.getPrivateKey()))); + if (iface.getListenPort() != 0) + fmt.format("listen_port=%d\n", config.getInterface().getListenPort()); + for (final Peer peer : config.getPeers()) { + if (peer.getPublicKey() != null) + fmt.format("public_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPublicKey()))); + if (peer.getPreSharedKey() != null) + fmt.format("preshared_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPreSharedKey()))); + if (peer.getEndpoint() != null) + fmt.format("endpoint=%s\n", peer.getResolvedEndpointString()); + if (peer.getPersistentKeepalive() != 0) + fmt.format("persistent_keepalive_interval=%d\n", peer.getPersistentKeepalive()); + for (final IPCidr addr : peer.getAllowedIPs()) { + fmt.format("allowed_ip=%s\n", addr.toString()); + } } + goConfig = fmt.toString(); } // Create the vpn tunnel with android API - VpnService.Builder builder = service.getBuilder(); + final VpnService.Builder builder = service.getBuilder(); builder.setSession(tunnel.getName()); for (final IPCidr addr : config.getInterface().getAddresses()) @@ -166,13 +169,13 @@ public final class GoBackend implements Backend { builder.setMtu(mtu); builder.setBlocking(true); - ParcelFileDescriptor tun = builder.establish(); + final ParcelFileDescriptor tun = builder.establish(); if (tun == null) throw new Exception("Unable to create tun device"); - currentTunnelHandle = wgTurnOn(tunnel.getName(), tun.detachFd(), fmt.toString()); + currentTunnelHandle = wgTurnOn(tunnel.getName(), tun.detachFd(), goConfig); if (currentTunnelHandle < 0) - throw new Exception("Unable to turn tunnel on (wgTurnOn return " + currentTunnelHandle + ")"); + throw new Exception("Unable to turn tunnel on (wgTurnOn return " + currentTunnelHandle + ')'); currentTunnel = tunnel; diff --git a/app/src/main/java/com/wireguard/android/backend/WgQuickBackend.java b/app/src/main/java/com/wireguard/android/backend/WgQuickBackend.java index b91d8476..b9eb3461 100644 --- a/app/src/main/java/com/wireguard/android/backend/WgQuickBackend.java +++ b/app/src/main/java/com/wireguard/android/backend/WgQuickBackend.java @@ -105,14 +105,15 @@ public final class WgQuickBackend implements Backend { } final String command = String.format("wg-quick %s '%s'", state.toString().toLowerCase(), tempFile.getAbsolutePath()); final int result = rootShell.run(null, command); + // noinspection ResultOfMethodCallIgnored tempFile.delete(); if (result != 0) throw new Exception("Unable to configure tunnel (wg-quick returned " + result + ')'); } - public final static class WgQuickChangeReceiver extends BroadcastReceiver { + public static final class WgQuickChangeReceiver extends BroadcastReceiver { @Override - public void onReceive(Context context, Intent intent) { + public void onReceive(final Context context, final Intent intent) { Log.d(TAG, "Refreshing tunnel states"); Application.getComponent().getTunnelManager().refreshTunnelStates(); } diff --git a/app/src/main/java/com/wireguard/android/fragment/TunnelEditorFragment.java b/app/src/main/java/com/wireguard/android/fragment/TunnelEditorFragment.java index a3760ed9..f0731587 100644 --- a/app/src/main/java/com/wireguard/android/fragment/TunnelEditorFragment.java +++ b/app/src/main/java/com/wireguard/android/fragment/TunnelEditorFragment.java @@ -109,10 +109,10 @@ public class TunnelEditorFragment extends BaseFragment { public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_action_save: - Config newConfig = new Config(); + final Config newConfig = new Config(); try { binding.getConfig().commitData(newConfig); - } catch (Exception e) { + } catch (final Exception e) { final String error = ExceptionLoggers.unwrap(e).getMessage(); final String tunnelName = tunnel == null ? binding.getConfig().getName() : tunnel.getName(); final String message = getString(R.string.config_save_error, tunnelName, error); @@ -202,8 +202,8 @@ public class TunnelEditorFragment extends BaseFragment { onSelectedTunnelChanged(null, getSelectedTunnel()); } else { tunnel = getSelectedTunnel(); - Config.Observable config = savedInstanceState.getParcelable(KEY_LOCAL_CONFIG); - String originalName = savedInstanceState.getString(KEY_ORIGINAL_NAME); + final Config.Observable config = savedInstanceState.getParcelable(KEY_LOCAL_CONFIG); + final String originalName = savedInstanceState.getString(KEY_ORIGINAL_NAME); if (tunnel != null && !tunnel.getName().equals(originalName)) onSelectedTunnelChanged(null, tunnel); else diff --git a/app/src/main/java/com/wireguard/android/fragment/TunnelListFragment.java b/app/src/main/java/com/wireguard/android/fragment/TunnelListFragment.java index 2b81a98a..9fc7346b 100644 --- a/app/src/main/java/com/wireguard/android/fragment/TunnelListFragment.java +++ b/app/src/main/java/com/wireguard/android/fragment/TunnelListFragment.java @@ -43,6 +43,7 @@ import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.zip.ZipEntry; @@ -82,7 +83,7 @@ public class TunnelListFragment extends BaseFragment { return; final ContentResolver contentResolver = activity.getContentResolver(); - final List<CompletableFuture<Tunnel>> futureTunnels = new ArrayList<>(); + final Collection<CompletableFuture<Tunnel>> futureTunnels = new ArrayList<>(); final List<Throwable> throwables = new ArrayList<>(); asyncWorker.supplyAsync(() -> { final String[] columns = {OpenableColumns.DISPLAY_NAME}; @@ -106,31 +107,32 @@ public class TunnelListFragment extends BaseFragment { throw new IllegalArgumentException("File must be .conf or .zip"); if (isZip) { - ZipInputStream zip = new ZipInputStream(contentResolver.openInputStream(uri)); - BufferedReader reader = new BufferedReader(new InputStreamReader(zip, StandardCharsets.UTF_8)); - ZipEntry entry; - while ((entry = zip.getNextEntry()) != null) { - if (entry.isDirectory()) - continue; - name = entry.getName(); - idx = name.lastIndexOf('/'); - if (idx >= 0) { - if (idx >= name.length() - 1) + try (ZipInputStream zip = new ZipInputStream(contentResolver.openInputStream(uri))) { + BufferedReader reader = new BufferedReader(new InputStreamReader(zip, StandardCharsets.UTF_8)); + ZipEntry entry; + while ((entry = zip.getNextEntry()) != null) { + if (entry.isDirectory()) continue; - name = name.substring(name.lastIndexOf('/') + 1); - } - if (name.toLowerCase().endsWith(".conf")) - name = name.substring(0, name.length() - ".conf".length()); - else - continue; - Config config = null; - try { - config = Config.from(reader); - } catch (Exception e) { - throwables.add(e); + name = entry.getName(); + idx = name.lastIndexOf('/'); + if (idx >= 0) { + if (idx >= name.length() - 1) + continue; + name = name.substring(name.lastIndexOf('/') + 1); + } + if (name.toLowerCase().endsWith(".conf")) + name = name.substring(0, name.length() - ".conf".length()); + else + continue; + Config config = null; + try { + config = Config.from(reader); + } catch (Exception e) { + throwables.add(e); + } + if (config != null) + futureTunnels.add(tunnelManager.create(name, config).toCompletableFuture()); } - if (config != null) - futureTunnels.add(tunnelManager.create(name, config).toCompletableFuture()); } } else { futureTunnels.add(tunnelManager.create(name, Config.from(contentResolver.openInputStream(uri))).toCompletableFuture()); @@ -146,15 +148,15 @@ public class TunnelListFragment extends BaseFragment { return CompletableFuture.allOf(futureTunnels.toArray(new CompletableFuture[futureTunnels.size()])); }).whenComplete((future, exception) -> { if (exception != null) { - this.onTunnelImportFinished(Collections.emptyList(), Collections.singletonList(exception)); + onTunnelImportFinished(Collections.emptyList(), Collections.singletonList(exception)); } else { future.whenComplete((ignored1, ignored2) -> { - ArrayList<Tunnel> tunnels = new ArrayList<>(futureTunnels.size()); - for (CompletableFuture<Tunnel> futureTunnel : futureTunnels) { + final List<Tunnel> tunnels = new ArrayList<>(futureTunnels.size()); + for (final CompletableFuture<Tunnel> futureTunnel : futureTunnels) { Tunnel tunnel = null; try { tunnel = futureTunnel.getNow(null); - } catch (Exception e) { + } catch (final Exception e) { throwables.add(e); } if (tunnel != null) @@ -240,7 +242,7 @@ public class TunnelListFragment extends BaseFragment { } } - private void onTunnelImportFinished(final List<Tunnel> tunnels, final List<Throwable> throwables) { + private void onTunnelImportFinished(final List<Tunnel> tunnels, final Collection<Throwable> throwables) { String message = null; for (final Throwable throwable : throwables) { diff --git a/app/src/main/java/com/wireguard/android/preference/ZipExporterPreference.java b/app/src/main/java/com/wireguard/android/preference/ZipExporterPreference.java index b10d8388..677c56c9 100644 --- a/app/src/main/java/com/wireguard/android/preference/ZipExporterPreference.java +++ b/app/src/main/java/com/wireguard/android/preference/ZipExporterPreference.java @@ -22,6 +22,7 @@ import com.wireguard.config.Config; import java.io.File; import java.io.FileOutputStream; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -39,7 +40,7 @@ public class ZipExporterPreference extends Preference { private final AsyncWorker asyncWorker; private final TunnelManager tunnelManager; - private String exportedFilePath = null; + private String exportedFilePath; @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) public ZipExporterPreference(final Context context, final AttributeSet attrs) { @@ -49,9 +50,19 @@ public class ZipExporterPreference extends Preference { tunnelManager = applicationComponent.getTunnelManager(); } + private static SettingsActivity getPrefActivity(final Preference preference) { + final Context context = preference.getContext(); + if (context instanceof ContextThemeWrapper) { + if (((ContextThemeWrapper) context).getBaseContext() instanceof SettingsActivity) { + return ((SettingsActivity) ((ContextThemeWrapper) context).getBaseContext()); + } + } + return null; + } + private void exportZip() { - List<Tunnel> tunnels = new ArrayList<>(tunnelManager.getTunnels()); - List<CompletableFuture<Config>> futureConfigs = new ArrayList<>(tunnels.size()); + final List<Tunnel> tunnels = new ArrayList<>(tunnelManager.getTunnels()); + final List<CompletableFuture<Config>> futureConfigs = new ArrayList<>(tunnels.size()); for (final Tunnel tunnel : tunnels) futureConfigs.add(tunnel.getConfigAsync().toCompletableFuture()); if (futureConfigs.isEmpty()) { @@ -65,9 +76,9 @@ public class ZipExporterPreference extends Preference { throw exception; final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); final File file = new File(path, "wireguard-export.zip"); - try { - path.mkdirs(); - final ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(file)); + if (!path.mkdirs()) + throw new IOException("Cannot create output directory"); + try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(file))) { for (int i = 0; i < futureConfigs.size(); ++i) { zip.putNextEntry(new ZipEntry(tunnels.get(i).getName() + ".conf")); zip.write(futureConfigs.get(i).getNow(null). @@ -76,6 +87,7 @@ public class ZipExporterPreference extends Preference { zip.closeEntry(); zip.close(); } catch (Exception e) { + // noinspection ResultOfMethodCallIgnored file.delete(); throw e; } @@ -84,7 +96,7 @@ public class ZipExporterPreference extends Preference { }); } - private void exportZipComplete(String filePath, Throwable throwable) { + private void exportZipComplete(final String filePath, final Throwable throwable) { if (throwable != null) { final String error = ExceptionLoggers.unwrap(throwable).getMessage(); final String message = getContext().getString(R.string.export_error, error); @@ -99,16 +111,6 @@ public class ZipExporterPreference extends Preference { } } - private SettingsActivity getPrefActivity(Preference preference) { - Context context = preference.getContext(); - if (context instanceof ContextThemeWrapper) { - if (((ContextThemeWrapper) context).getBaseContext() instanceof SettingsActivity) { - return ((SettingsActivity) ((ContextThemeWrapper) context).getBaseContext()); - } - } - return null; - } - @Override public CharSequence getSummary() { if (exportedFilePath == null) diff --git a/app/src/main/java/com/wireguard/config/Attribute.java b/app/src/main/java/com/wireguard/config/Attribute.java index 2d8070ac..726eaa1a 100644 --- a/app/src/main/java/com/wireguard/config/Attribute.java +++ b/app/src/main/java/com/wireguard/config/Attribute.java @@ -6,7 +6,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.util.HashMap; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; @@ -28,9 +27,11 @@ enum Attribute { PRIVATE_KEY("PrivateKey"), PUBLIC_KEY("PublicKey"); + private static final String[] EMPTY_LIST = new String[0]; private static final Map<String, Attribute> KEY_MAP; + private static final Pattern LIST_SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*"); + private static final Method NUMERIC_ADDRESS_PARSER; private static final Pattern SEPARATOR_PATTERN = Pattern.compile("\\s|="); - private static Method parseNumericAddressMethod; static { KEY_MAP = new HashMap<>(Attribute.values().length); @@ -41,8 +42,8 @@ enum Attribute { static { try { - parseNumericAddressMethod = InetAddress.class.getMethod("parseNumericAddress", new Class[]{String.class}); - } catch (Exception e) { + NUMERIC_ADDRESS_PARSER = InetAddress.class.getMethod("parseNumericAddress", String.class); + } catch (final Exception e) { throw new RuntimeException(e); } } @@ -55,8 +56,8 @@ enum Attribute { this.token = token; } - public static <T> String listToString(final List<T> list) { - return TextUtils.join(", ", list); + public static <T> String iterableToString(final Iterable<T> iterable) { + return TextUtils.join(", ", iterable); } public static Attribute match(final CharSequence line) { @@ -67,10 +68,10 @@ enum Attribute { if (address == null || address.isEmpty()) throw new IllegalArgumentException("Empty address"); try { - return (InetAddress) parseNumericAddressMethod.invoke(null, new Object[]{address}); - } catch (IllegalAccessException e) { + return (InetAddress) NUMERIC_ADDRESS_PARSER.invoke(null, address); + } catch (final IllegalAccessException e) { throw new RuntimeException(e); - } catch (InvocationTargetException e) { + } catch (final InvocationTargetException e) { if (e.getCause() instanceof IllegalArgumentException) throw (IllegalArgumentException) e.getCause(); else @@ -80,8 +81,8 @@ enum Attribute { public static String[] stringToList(final String string) { if (string == null) - return new String[0]; - return string.trim().split("\\s*,\\s*"); + return EMPTY_LIST; + return LIST_SEPARATOR_PATTERN.split(string.trim()); } public String composeWith(final Object value) { @@ -92,8 +93,8 @@ enum Attribute { return String.format(Locale.getDefault(), "%s = %d%n", token, value); } - public <T> String composeWith(final List<T> value) { - return String.format("%s = %s%n", token, listToString(value)); + public <T> String composeWith(final Iterable<T> value) { + return String.format("%s = %s%n", token, iterableToString(value)); } public String parse(final CharSequence line) { diff --git a/app/src/main/java/com/wireguard/config/Config.java b/app/src/main/java/com/wireguard/config/Config.java index 7e6ff77c..ca2d3b1f 100644 --- a/app/src/main/java/com/wireguard/config/Config.java +++ b/app/src/main/java/com/wireguard/config/Config.java @@ -90,7 +90,7 @@ public class Config { private Interface.Observable observableInterface; private ObservableList<Peer.Observable> observablePeers; - public Observable(Config parent, String name) { + public Observable(final Config parent, final String name) { this.name = name; loadData(parent); } @@ -102,11 +102,11 @@ public class Config { in.readTypedList(observablePeers, Peer.Observable.CREATOR); } - public void commitData(Config parent) { - this.observableInterface.commitData(parent.interfaceSection); - List<Peer> newPeers = new ArrayList<>(this.observablePeers.size()); - for (Peer.Observable observablePeer : this.observablePeers) { - Peer peer = new Peer(); + public void commitData(final Config parent) { + observableInterface.commitData(parent.interfaceSection); + final List<Peer> newPeers = new ArrayList<>(observablePeers.size()); + for (final Peer.Observable observablePeer : observablePeers) { + final Peer peer = new Peer(); observablePeer.commitData(peer); newPeers.add(peer); } @@ -134,16 +134,16 @@ public class Config { return observablePeers; } - public void loadData(Config parent) { - this.observableInterface = new Interface.Observable(parent == null ? null : parent.interfaceSection); - this.observablePeers = new ObservableArrayList<>(); + protected void loadData(final Config parent) { + observableInterface = new Interface.Observable(parent == null ? null : parent.interfaceSection); + observablePeers = new ObservableArrayList<>(); if (parent != null) { - for (Peer peer : parent.getPeers()) - this.observablePeers.add(new Peer.Observable(peer)); + for (final Peer peer : parent.getPeers()) + observablePeers.add(new Peer.Observable(peer)); } } - public void setName(String name) { + public void setName(final String name) { this.name = name; notifyPropertyChanged(BR.name); } diff --git a/app/src/main/java/com/wireguard/config/IPCidr.java b/app/src/main/java/com/wireguard/config/IPCidr.java index 41d43cd6..a0135d15 100644 --- a/app/src/main/java/com/wireguard/config/IPCidr.java +++ b/app/src/main/java/com/wireguard/config/IPCidr.java @@ -6,17 +6,17 @@ import java.net.InetAddress; import java.util.Locale; public class IPCidr { - private InetAddress address; + private final InetAddress address; private int cidr; public IPCidr(String in) { cidr = -1; - int slash = in.lastIndexOf('/'); + final int slash = in.lastIndexOf('/'); if (slash != -1 && slash < in.length() - 1) { try { cidr = Integer.parseInt(in.substring(slash + 1), 10); in = in.substring(0, slash); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } address = Attribute.parseIPString(in); diff --git a/app/src/main/java/com/wireguard/config/Interface.java b/app/src/main/java/com/wireguard/config/Interface.java index ff69ccaf..37186206 100644 --- a/app/src/main/java/com/wireguard/config/Interface.java +++ b/app/src/main/java/com/wireguard/config/Interface.java @@ -9,7 +9,7 @@ import com.wireguard.android.BR; import com.wireguard.crypto.Keypair; import java.net.InetAddress; -import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; /** @@ -17,30 +17,31 @@ import java.util.List; */ public class Interface { - private List<IPCidr> addressList; - private List<InetAddress> dnsList; + private final List<IPCidr> addressList; + private final List<InetAddress> dnsList; private Keypair keypair; private int listenPort; private int mtu; + public Interface() { - addressList = new LinkedList<>(); - dnsList = new LinkedList<>(); + addressList = new ArrayList<>(); + dnsList = new ArrayList<>(); } - private void addAddresses(String[] addresses) { + private void addAddresses(final String[] addresses) { if (addresses != null && addresses.length > 0) { for (final String addr : addresses) { if (addr.isEmpty()) throw new IllegalArgumentException("Address is empty"); - this.addressList.add(new IPCidr(addr)); + addressList.add(new IPCidr(addr)); } } } - private void addDnses(String[] dnses) { + private void addDnses(final String[] dnses) { if (dnses != null && dnses.length > 0) { for (final String dns : dnses) { - this.dnsList.add(Attribute.parseIPString(dns)); + dnsList.add(Attribute.parseIPString(dns)); } } } @@ -48,7 +49,7 @@ public class Interface { private String getAddressString() { if (addressList.isEmpty()) return null; - return Attribute.listToString(addressList); + return Attribute.iterableToString(addressList); } public IPCidr[] getAddresses() { @@ -58,11 +59,11 @@ public class Interface { private String getDnsString() { if (dnsList.isEmpty()) return null; - return Attribute.listToString(getDnsStrings()); + return Attribute.iterableToString(getDnsStrings()); } private List<String> getDnsStrings() { - List<String> strings = new LinkedList<>(); + final List<String> strings = new ArrayList<>(); for (final InetAddress addr : dnsList) strings.add(addr.getHostAddress()); return strings; @@ -106,31 +107,38 @@ public class Interface { public void parse(final String line) { final Attribute key = Attribute.match(line); - if (key == Attribute.ADDRESS) - addAddresses(key.parseList(line)); - else if (key == Attribute.DNS) - addDnses(key.parseList(line)); - else if (key == Attribute.LISTEN_PORT) - setListenPortString(key.parse(line)); - else if (key == Attribute.MTU) - setMtuString(key.parse(line)); - else if (key == Attribute.PRIVATE_KEY) - setPrivateKey(key.parse(line)); - else - throw new IllegalArgumentException(line); + switch (key) { + case ADDRESS: + addAddresses(key.parseList(line)); + break; + case DNS: + addDnses(key.parseList(line)); + break; + case LISTEN_PORT: + setListenPortString(key.parse(line)); + break; + case MTU: + setMtuString(key.parse(line)); + break; + case PRIVATE_KEY: + setPrivateKey(key.parse(line)); + break; + default: + throw new IllegalArgumentException(line); + } } private void setAddressString(final String addressString) { - this.addressList.clear(); + addressList.clear(); addAddresses(Attribute.stringToList(addressString)); } private void setDnsString(final String dnsString) { - this.dnsList.clear(); + dnsList.clear(); addDnses(Attribute.stringToList(dnsString)); } - private void setListenPort(int listenPort) { + private void setListenPort(final int listenPort) { this.listenPort = listenPort; } @@ -141,7 +149,7 @@ public class Interface { setListenPort(0); } - private void setMtu(int mtu) { + private void setMtu(final int mtu) { this.mtu = mtu; } @@ -155,10 +163,7 @@ public class Interface { private void setPrivateKey(String privateKey) { if (privateKey != null && privateKey.isEmpty()) privateKey = null; - if (privateKey == null) - keypair = null; - else - keypair = new Keypair(privateKey); + keypair = privateKey == null ? null : new Keypair(privateKey); } @Override @@ -196,7 +201,7 @@ public class Interface { private String privateKey; private String publicKey; - public Observable(Interface parent) { + public Observable(final Interface parent) { if (parent != null) loadData(parent); } @@ -210,12 +215,12 @@ public class Interface { mtu = in.readString(); } - public void commitData(Interface parent) { - parent.setAddressString(this.addresses); - parent.setDnsString(this.dnses); - parent.setPrivateKey(this.privateKey); - parent.setListenPortString(this.listenPort); - parent.setMtuString(this.mtu); + public void commitData(final Interface parent) { + parent.setAddressString(addresses); + parent.setDnsString(dnses); + parent.setPrivateKey(privateKey); + parent.setListenPortString(listenPort); + parent.setMtuString(mtu); loadData(parent); notifyChange(); } @@ -226,7 +231,7 @@ public class Interface { } public void generateKeypair() { - Keypair keypair = new Keypair(); + final Keypair keypair = new Keypair(); privateKey = keypair.getPrivateKey(); publicKey = keypair.getPublicKey(); notifyPropertyChanged(BR.privateKey); @@ -263,42 +268,42 @@ public class Interface { return publicKey; } - public void loadData(Interface parent) { - this.addresses = parent.getAddressString(); - this.dnses = parent.getDnsString(); - this.publicKey = parent.getPublicKey(); - this.privateKey = parent.getPrivateKey(); - this.listenPort = parent.getListenPortString(); - this.mtu = parent.getMtuString(); + protected void loadData(final Interface parent) { + addresses = parent.getAddressString(); + dnses = parent.getDnsString(); + publicKey = parent.getPublicKey(); + privateKey = parent.getPrivateKey(); + listenPort = parent.getListenPortString(); + mtu = parent.getMtuString(); } - public void setAddresses(String addresses) { + public void setAddresses(final String addresses) { this.addresses = addresses; notifyPropertyChanged(BR.addresses); } - public void setDnses(String dnses) { + public void setDnses(final String dnses) { this.dnses = dnses; notifyPropertyChanged(BR.dnses); } - public void setListenPort(String listenPort) { + public void setListenPort(final String listenPort) { this.listenPort = listenPort; notifyPropertyChanged(BR.listenPort); } - public void setMtu(String mtu) { + public void setMtu(final String mtu) { this.mtu = mtu; notifyPropertyChanged(BR.mtu); } - public void setPrivateKey(String privateKey) { + public void setPrivateKey(final String privateKey) { this.privateKey = privateKey; try { - this.publicKey = new Keypair(privateKey).getPublicKey(); - } catch (IllegalArgumentException ignored) { - this.publicKey = ""; + publicKey = new Keypair(privateKey).getPublicKey(); + } catch (final IllegalArgumentException ignored) { + publicKey = ""; } notifyPropertyChanged(BR.privateKey); diff --git a/app/src/main/java/com/wireguard/config/Peer.java b/app/src/main/java/com/wireguard/config/Peer.java index 9f71089f..413a8d6e 100644 --- a/app/src/main/java/com/wireguard/config/Peer.java +++ b/app/src/main/java/com/wireguard/config/Peer.java @@ -13,7 +13,7 @@ import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; -import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -22,19 +22,20 @@ import java.util.Locale; */ public class Peer { - private List<IPCidr> allowedIPsList; + private final List<IPCidr> allowedIPsList; private InetSocketAddress endpoint; private int persistentKeepalive; private String preSharedKey; private String publicKey; + public Peer() { - allowedIPsList = new LinkedList<>(); + allowedIPsList = new ArrayList<>(); } - private void addAllowedIPs(String[] allowedIPs) { + private void addAllowedIPs(final String[] allowedIPs) { if (allowedIPs != null && allowedIPs.length > 0) { for (final String allowedIP : allowedIPs) { - this.allowedIPsList.add(new IPCidr(allowedIP)); + allowedIPsList.add(new IPCidr(allowedIP)); } } } @@ -46,7 +47,7 @@ public class Peer { private String getAllowedIPsString() { if (allowedIPsList.isEmpty()) return null; - return Attribute.listToString(allowedIPsList); + return Attribute.iterableToString(allowedIPsList); } public InetSocketAddress getEndpoint() { @@ -97,38 +98,45 @@ public class Peer { public void parse(final String line) { final Attribute key = Attribute.match(line); - if (key == Attribute.ALLOWED_IPS) - addAllowedIPs(key.parseList(line)); - else if (key == Attribute.ENDPOINT) - setEndpointString(key.parse(line)); - else if (key == Attribute.PERSISTENT_KEEPALIVE) - setPersistentKeepaliveString(key.parse(line)); - else if (key == Attribute.PRESHARED_KEY) - setPreSharedKey(key.parse(line)); - else if (key == Attribute.PUBLIC_KEY) - setPublicKey(key.parse(line)); - else - throw new IllegalArgumentException(line); + switch (key) { + case ALLOWED_IPS: + addAllowedIPs(key.parseList(line)); + break; + case ENDPOINT: + setEndpointString(key.parse(line)); + break; + case PERSISTENT_KEEPALIVE: + setPersistentKeepaliveString(key.parse(line)); + break; + case PRESHARED_KEY: + setPreSharedKey(key.parse(line)); + break; + case PUBLIC_KEY: + setPublicKey(key.parse(line)); + break; + default: + throw new IllegalArgumentException(line); + } } private void setAllowedIPsString(final String allowedIPsString) { - this.allowedIPsList.clear(); + allowedIPsList.clear(); addAllowedIPs(Attribute.stringToList(allowedIPsString)); } - private void setEndpoint(InetSocketAddress endpoint) { + private void setEndpoint(final InetSocketAddress endpoint) { this.endpoint = endpoint; } private void setEndpointString(final String endpoint) { if (endpoint != null && !endpoint.isEmpty()) { - InetSocketAddress constructedEndpoint; + final InetSocketAddress constructedEndpoint; if (endpoint.indexOf('/') != -1 || endpoint.indexOf('?') != -1 || endpoint.indexOf('#') != -1) throw new IllegalArgumentException("Forbidden characters in endpoint"); - URI uri; + final URI uri; try { uri = new URI("wg://" + endpoint); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } constructedEndpoint = InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort()); @@ -137,11 +145,11 @@ public class Peer { setEndpoint(null); } - private void setPersistentKeepalive(int persistentKeepalive) { + private void setPersistentKeepalive(final int persistentKeepalive) { this.persistentKeepalive = persistentKeepalive; } - private void setPersistentKeepaliveString(String persistentKeepalive) { + private void setPersistentKeepaliveString(final String persistentKeepalive) { if (persistentKeepalive != null && !persistentKeepalive.isEmpty()) setPersistentKeepalive(Integer.parseInt(persistentKeepalive, 10)); else @@ -198,7 +206,7 @@ public class Peer { private String preSharedKey; private String publicKey; - public Observable(Peer parent) { + public Observable(final Peer parent) { loadData(parent); } @@ -214,12 +222,12 @@ public class Peer { return new Observable(new Peer()); } - public void commitData(Peer parent) { - parent.setAllowedIPsString(this.allowedIPs); - parent.setEndpointString(this.endpoint); - parent.setPersistentKeepaliveString(this.persistentKeepalive); - parent.setPreSharedKey(this.preSharedKey); - parent.setPublicKey(this.publicKey); + public void commitData(final Peer parent) { + parent.setAllowedIPsString(allowedIPs); + parent.setEndpointString(endpoint); + parent.setPersistentKeepaliveString(persistentKeepalive); + parent.setPreSharedKey(preSharedKey); + parent.setPublicKey(publicKey); if (parent.getPublicKey() == null) throw new IllegalArgumentException("Peer public key may not be empty"); loadData(parent); @@ -256,35 +264,35 @@ public class Peer { return publicKey; } - public void loadData(Peer parent) { - this.allowedIPs = parent.getAllowedIPsString(); - this.endpoint = parent.getEndpointString(); - this.persistentKeepalive = parent.getPersistentKeepaliveString(); - this.preSharedKey = parent.getPreSharedKey(); - this.publicKey = parent.getPublicKey(); + protected void loadData(final Peer parent) { + allowedIPs = parent.getAllowedIPsString(); + endpoint = parent.getEndpointString(); + persistentKeepalive = parent.getPersistentKeepaliveString(); + preSharedKey = parent.getPreSharedKey(); + publicKey = parent.getPublicKey(); } - public void setAllowedIPs(String allowedIPs) { + public void setAllowedIPs(final String allowedIPs) { this.allowedIPs = allowedIPs; notifyPropertyChanged(BR.allowedIPs); } - public void setEndpoint(String endpoint) { + public void setEndpoint(final String endpoint) { this.endpoint = endpoint; notifyPropertyChanged(BR.endpoint); } - public void setPersistentKeepalive(String persistentKeepalive) { + public void setPersistentKeepalive(final String persistentKeepalive) { this.persistentKeepalive = persistentKeepalive; notifyPropertyChanged(BR.persistentKeepalive); } - public void setPreSharedKey(String preSharedKey) { + public void setPreSharedKey(final String preSharedKey) { this.preSharedKey = preSharedKey; notifyPropertyChanged(BR.preSharedKey); } - public void setPublicKey(String publicKey) { + public void setPublicKey(final String publicKey) { this.publicKey = publicKey; notifyPropertyChanged(BR.publicKey); } |