Repository: pedrovgs/AndroidWiFiADB Branch: master Commit: c54f1e8dba38 Files: 37 Total size: 91.9 KB Directory structure: gitextract_6omu7d4f/ ├── .gitignore ├── .travis.yml ├── AndroidWiFiADB.iml ├── LICENSE.txt ├── README.md ├── art/ │ └── AWADBIcon.xcf ├── build.gradle ├── config/ │ └── checkstyle/ │ └── checkstyle.xml ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── settigs.gradle └── src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── github/ │ │ └── pedrovgs/ │ │ └── androidwifiadb/ │ │ ├── AndroidWiFiADB.java │ │ ├── Device.java │ │ ├── action/ │ │ │ └── AndroidWiFiADBAction.java │ │ ├── adb/ │ │ │ ├── ADB.java │ │ │ ├── ADBParser.java │ │ │ └── CommandLine.java │ │ ├── util/ │ │ │ └── NotificationUtils.java │ │ ├── view/ │ │ │ ├── NotificationView.java │ │ │ └── View.java │ │ └── window/ │ │ ├── ActionButtonListener.java │ │ ├── AndroidDevicesTableModel.java │ │ ├── AndroidWiFiADBWindow.form │ │ ├── AndroidWiFiADBWindow.java │ │ ├── CardLayoutDevices.java │ │ ├── ConnectDisconnectEditor.java │ │ ├── ConnectDisconnectPanel.java │ │ ├── ConnectDisconnectRenderer.java │ │ └── DeviceAction.java │ └── resources/ │ └── META-INF/ │ └── plugin.xml └── test/ └── java/ └── com/ └── github/ └── pedrovgs/ └── androidwifiadb/ ├── AndroidWiFiADBTest.java ├── UnitTest.java ├── adb/ │ └── ADBParserTest.java └── window/ └── AndroidDevicesTableModelTest.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # IntelliJ out/ .idea/ target/ *.iml local.properties ### Java ### *.class classes/ # Package Files # *.jar ### Gradle ### .gradle build/ ### Specific ### *.zip # Ignore Gradle GUI config gradle-app.setting # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) !gradle-wrapper.jar # Avoid ignoring AndroidWiFiADB.iml file to be able to import the project into any IntelliJ IDE and run/debug the pulgin without problems !AndroidWiFiADB.iml ================================================ FILE: .travis.yml ================================================ language: java jdk: oraclejdk7 env: matrix: - TERM=dumb after_success: - ./gradlew test jacocoTestReport coveralls script: ./gradlew checkstyle build ================================================ FILE: AndroidWiFiADB.iml ================================================ ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: README.md ================================================ Android WiFi ADB - IntelliJ/Android Studio Plugin [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Android%20WiFi%20ADB-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/2654) ================================================= ![Android WiFi ADB][1] **IntelliJ and Android Studio plugin** created to **quickly connect your Android device over WiFi** to install, run and debug your applications without a USB connected. Press one button and forget about your USB cable. **Android WiFI ADB plugin adds a button ![Android WiFi ADB Button][5] to your IntelliJ/Android Studio Toolbar** to connect your device to your computer over WiFi. *To use this plugin the project opened in your IntelliJ/Android Studio has to be an Android project configured with the Android SDK.* **Archived repository:** Maintaining this project up to date for all the different Android devices without having access to the physical devices is not possible at all right now. Most of the bugs reported ar related to the adb installation and not to the plugin code so this repository will keep archived for now. Screenshots ----------- Connect all devices button: ![Android WiFi ADB Usage][2] Devices dashboard: ![Android Devices Window][7] Usage ----- Connect your device to your computer using a USB cable. Then press the button, and a notification will pop up saying that the phone has been connected. Disconnect your USB once the plugin shows your device is connected. Open the Android WiFi ADB tab at the right side to see all the devices and manage your connections. Your device will be connected over WiFi now. You can now deploy, run and debug your device using your WiFi connection. Remember that your device and your computer have to be in the same WiFi connection. Also, you have to first connect your device with a USB every time you open Android Studio, for setting up the connection over WiFi. If you want to handle your devices connection individually, open the Android WiFi ADB dashboard you will find at the right of your IDE. Installation ------------ Download and install **Android WiFi ADB** directly from Intellij / Android Studio: `Preferences/Settings->Plugins->Browse Repositories` Alternatively, you can [download the plugin][6] from the JetBrains plugin site and install it manually in: `Preferences/Settings->Plugins->Install plugin from disk`. Build the project ----------------- If you need some information about how to build this project review [IntelliJ Idea's Gradle Plugin documentation](https://github.com/JetBrains/gradle-intellij-plugin). Do you want to contribute? -------------------------- Please, do it! If you have any improvement or you've found any bug, send a pull request with the code or open an issue :) Libraries used on the sample project ------------------------------------ * [JUnit][3] * [Mockito][4] Developed By ------------ * Pedro Vicente Gómez Sánchez - Follow me on Twitter Add me to Linkedin License ------- Copyright 2015 Pedro Vicente Gómez Sánchez 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. [1]: ./art/AndroidWiFiADBIcon.png [2]: ./art/screenshot1.gif [3]: https://github.com/junit-team/junit [4]: https://github.com/mockito/mockito [5]: ./art/sampleButton.png [6]: https://plugins.jetbrains.com/plugin/7983 [7]: ./art/android_devices_window.png ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenCentral() } } plugins { id "org.jetbrains.intellij" version "0.0.25" } apply plugin: 'org.jetbrains.intellij' apply plugin: 'java' apply plugin: 'checkstyle' apply plugin: 'jacoco' group 'com.github.pedrovgs' version '2.5-SNAPSHOT' sourceCompatibility = 1.6 repositories { mavenCentral() } intellij { version '14.1.5' pluginName 'AndroidWiFiADB' plugins 'android' updateSinceUntilBuild false } dependencies { compile 'junit:junit:4.12' compile 'org.mockito:mockito-all:1.10.19' } task checkstyle(type: Checkstyle) { configFile file("${project.rootDir}/config/checkstyle/checkstyle.xml") source 'src' include '**/*.java' exclude '**/gen/**' classpath = files() } ================================================ FILE: config/checkstyle/checkstyle.xml ================================================ ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Tue Dec 15 00:42:48 CET 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.7-all.zip ================================================ FILE: gradle.properties ================================================ ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settigs.gradle ================================================ rootProject.name = 'AndroidWiFiADB' ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/AndroidWiFiADB.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb; import com.github.pedrovgs.androidwifiadb.adb.ADB; import com.github.pedrovgs.androidwifiadb.view.View; import com.intellij.openapi.project.Project; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; public class AndroidWiFiADB { private static final Set DEVICES = new HashSet(); private final ADB adb; private final View view; public AndroidWiFiADB(ADB adb, View view) { this.adb = adb; this.view = view; } public void connectDevices() { if (!isADBInstalled()) { view.showADBNotInstalledNotification(); return; } DEVICES.clear(); DEVICES.addAll(adb.getDevicesConnectedByUSB()); if (DEVICES.isEmpty()) { view.showNoConnectedDevicesNotification(); return; } DEVICES.addAll(adb.connectDevices(DEVICES)); showConnectionResultNotification(DEVICES); } public boolean refreshDevicesList() { if (!isADBInstalled()) { return false; } removeNotConnectedDevices(); final Collection connected = adb.getDevicesConnectedByUSB(); for (Device connectedDevice : connected) { if (!checkDeviceExistance(connectedDevice)) { connectedDevice.setIp(adb.getDeviceIp(connectedDevice)); DEVICES.add(connectedDevice); } else { updateDeviceConnectionState(connectedDevice); } } return true; } private void removeNotConnectedDevices() { List connectedDevices = new LinkedList(); for (Device device : DEVICES) { if (device.isConnected()) { connectedDevices.add(device); } } DEVICES.clear(); DEVICES.addAll(connectedDevices); } public Collection getDevices() { return DEVICES; } public void connectDevice(Device device) { if (!isADBInstalled()) { view.showADBNotInstalledNotification(); return; } Collection connectedDevices = new ArrayList(); connectedDevices.add(device); connectedDevices = adb.connectDevices(connectedDevices); for (Device connected : connectedDevices) { updateDeviceConnectionState(connected); } showConnectionResultNotification(connectedDevices); } public void disconnectDevice(Device device) { if (!isADBInstalled()) { view.showADBNotInstalledNotification(); return; } List disconnectedDevices = new ArrayList(); disconnectedDevices.add(device); disconnectedDevices = adb.disconnectDevices(disconnectedDevices); for (Device disconnected : disconnectedDevices) { updateDeviceConnectionState(disconnected); } showDisconnectionResultNotification(disconnectedDevices); } public void updateProject(Project project) { adb.updateProject(project); } private void updateDeviceConnectionState(final Device updatedDevice) { DEVICES.add(updatedDevice); } private boolean checkDeviceExistance(Device connectedDevice) { boolean deviceExists = false; for (Device device : DEVICES) { if (connectedDevice.getId().equals(device.getId())) { deviceExists = true; } } return deviceExists; } private boolean isADBInstalled() { return adb.isInstalled(); } private void showConnectionResultNotification(Collection devices) { for (Device device : devices) { if (device.isConnected()) { view.showConnectedDeviceNotification(device); } else { view.showErrorConnectingDeviceNotification(device); } } } private void showDisconnectionResultNotification(Collection devices) { for (Device device : devices) { if (!device.isConnected()) { view.showDisconnectedDeviceNotification(device); } else { view.showErrorDisconnectingDeviceNotification(device); } } } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/Device.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb; public class Device { private final String id; private String name; private String ip = ""; private boolean connected; public Device(String name, String id) { this.name = name; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public boolean isConnected() { return connected; } public void setConnected(boolean connected) { this.connected = connected; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Device device = (Device) o; return id.equals(device.id); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return name; } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/action/AndroidWiFiADBAction.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.action; import com.github.pedrovgs.androidwifiadb.AndroidWiFiADB; import com.github.pedrovgs.androidwifiadb.view.NotificationView; import com.github.pedrovgs.androidwifiadb.adb.ADB; import com.github.pedrovgs.androidwifiadb.adb.ADBParser; import com.github.pedrovgs.androidwifiadb.adb.CommandLine; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; public class AndroidWiFiADBAction extends AnAction { private final AndroidWiFiADB androidWifiADB; public AndroidWiFiADBAction() { CommandLine commandLine = new CommandLine(); ADBParser adbParser = new ADBParser(); ADB adb = new ADB(commandLine, adbParser); this.androidWifiADB = new AndroidWiFiADB(adb, new NotificationView()); } public void actionPerformed(final AnActionEvent event) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { androidWifiADB.updateProject(event.getProject()); androidWifiADB.connectDevices(); } }); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/adb/ADB.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.adb; import com.github.pedrovgs.androidwifiadb.Device; import com.intellij.openapi.project.Project; import java.io.File; import java.util.Collection; import java.util.List; import org.jetbrains.android.sdk.AndroidSdkUtils; public class ADB { private static final String TCPIP_PORT = "5555"; private final CommandLine commandLine; private final ADBParser adbParser; private Project project; public ADB(CommandLine commandLine, ADBParser adbParser) { this.commandLine = commandLine; this.adbParser = adbParser; } public void updateProject(Project project) { this.project = project; } public boolean isInstalled() { return AndroidSdkUtils.isAndroidSdkAvailable(); } public Collection getDevicesConnectedByUSB() { String getDevicesCommand = getCommand("devices -l"); String adbDevicesOutput = commandLine.executeCommand(getDevicesCommand); return adbParser.parseGetDevicesOutput(adbDevicesOutput); } public Collection connectDevices(Collection devices) { for (Device device : devices) { boolean connected = connectDeviceByIp(device); device.setConnected(connected); } return devices; } public List disconnectDevices(List devices) { for (Device device : devices) { boolean disconnected = disconnectDevice(device.getIp()); device.setConnected(disconnected); } return devices; } private boolean connectDeviceByIp(Device device) { String deviceIp = getDeviceIp(device); if (deviceIp.isEmpty()) { return false; } else { return connectDevice(deviceIp); } } private boolean disconnectDevice(String deviceIp) { enableTCPCommand(); String connectDeviceCommand = getCommand("disconnect " + deviceIp); return commandLine.executeCommand(connectDeviceCommand).isEmpty(); } public String getDeviceIp(Device device) { String getDeviceIpCommand = getCommand("-s " + device.getId() + " shell ip -f inet addr show wlan0"); String ipInfoOutput = commandLine.executeCommand(getDeviceIpCommand); return adbParser.parseGetDeviceIp(ipInfoOutput); } private void enableTCPCommand() { if (!checkTCPCommandExecuted()) { String enableTCPCommand = getCommand("tcpip " + TCPIP_PORT); commandLine.executeCommand(enableTCPCommand); } } private boolean checkTCPCommandExecuted() { String getPropCommand = getCommand("adb shell getprop | grep adb"); String getPropOutput = commandLine.executeCommand(getPropCommand); String adbTcpPort = adbParser.parseAdbServiceTcpPort(getPropOutput); return TCPIP_PORT.equals(adbTcpPort); } private boolean connectDevice(String deviceIp) { String enableTCPCommand = getCommand("tcpip 5555"); commandLine.executeCommand(enableTCPCommand); String connectDeviceCommand = getCommand("connect " + deviceIp); String connectOutput = commandLine.executeCommand(connectDeviceCommand); return connectOutput.contains("connected"); } private String getAdbPath() { String adbPath = ""; File adbFile = AndroidSdkUtils.getAdb(project); if (adbFile != null) { adbPath = adbFile.getAbsolutePath(); } return adbPath; } private String getCommand(String command) { return getAdbPath() + " " + command; } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/adb/ADBParser.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.adb; import com.github.pedrovgs.androidwifiadb.Device; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ADBParser { private static final String MODEL_INDICATOR = "model:"; private static final String DEVICE_INDICATOR = "device:"; private static final String IP_SEPARATOR = "."; private static final String END_DEVICE_IP_INDICATOR = "/"; private static final String START_DEVICE_IP_INDICATOR = "inet"; private static final String ERROR_PARSING_DEVICE_IP_KEY = "Object"; private static final String DAEMON_INDICATOR = "daemon"; private static final String START_TCPIP_PORT_INDICATOR = "[service.adb.tcp.port]: ["; private static final String DEVICE_NOT_FOUND = "error: device '(null)' not found"; public List parseGetDevicesOutput(String adbDevicesOutput) { List devices = new LinkedList(); if (adbDevicesOutput.contains(DAEMON_INDICATOR)) { return devices; } String[] splittedOutput = adbDevicesOutput.split("\\n"); if (splittedOutput.length == 1) { return devices; } for (int i = 1; i < splittedOutput.length; i++) { String line = splittedOutput[i]; String[] deviceLine = line.split("\\t"); String id = deviceLine[0].substring(0, deviceLine[0].indexOf(" ")); if (id.contains(IP_SEPARATOR)) { continue; } String name = parseDeviceName(line); Device device = new Device(name, id); devices.add(device); } return devices; } public String parseGetDeviceIp(String ipInfo) { if (ipInfo.isEmpty() || ipInfo.contains(ERROR_PARSING_DEVICE_IP_KEY)) { return ""; } try { int start = ipInfo.indexOf(START_DEVICE_IP_INDICATOR) + 5; int end = ipInfo.indexOf(END_DEVICE_IP_INDICATOR); return ipInfo.substring(start, end); } catch (StringIndexOutOfBoundsException e) { System.out.println(e); return ""; } } public String parseAdbServiceTcpPort(String getPropOutput) { if (getPropOutput.isEmpty() || getPropOutput.contains(DEVICE_NOT_FOUND) || !getPropOutput.contains(START_TCPIP_PORT_INDICATOR)) { return ""; } Matcher portMatcher = Pattern.compile("(?<=\\[(service\\.adb\\.tcp\\.port).: \\[)([^\\]]+)(?=\\])") .matcher(getPropOutput); if (portMatcher.find()) { return portMatcher.group(0); } return ""; } private String parseDeviceName(String line) { int start = line.indexOf(MODEL_INDICATOR) + MODEL_INDICATOR.length(); int end = line.indexOf(DEVICE_INDICATOR) - 1; if (end < 0) { end = line.length(); } return line.substring(start, end); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/adb/CommandLine.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.adb; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CommandLine { public String executeCommand(String command) { Process process; StringBuilder stringBuilder = new StringBuilder(); try { process = Runtime.getRuntime().exec(command); process.waitFor(); InputStreamReader in = new InputStreamReader(process.getInputStream()); BufferedReader reader = new BufferedReader(in); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); } } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/util/NotificationUtils.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.util; import com.intellij.notification.Notification; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; public class NotificationUtils { private static final String ANDROID_WIFI_ADB_TITLE = "Android WiFi ADB"; private static final NotificationGroup NOTIFICATION_GROUP = NotificationGroup.balloonGroup(ANDROID_WIFI_ADB_TITLE); public static void showNotification(final String message, final NotificationType type) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Notification notification = NOTIFICATION_GROUP.createNotification(ANDROID_WIFI_ADB_TITLE, message, type, null); Notifications.Bus.notify(notification); } }); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/view/NotificationView.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.view; import com.github.pedrovgs.androidwifiadb.Device; import com.intellij.notification.NotificationType; import static com.github.pedrovgs.androidwifiadb.util.NotificationUtils.showNotification; public class NotificationView implements View { @Override public void showNoConnectedDevicesNotification() { showNotification("There are no devices connected. Review your USB connection and try again.", NotificationType.INFORMATION); } @Override public void showConnectedDeviceNotification(Device device) { showNotification("Device '" + device.getName() + "' connected.", NotificationType.INFORMATION); } @Override public void showDisconnectedDeviceNotification(Device device) { showNotification("Device '" + device.getName() + "' disconnected.", NotificationType.INFORMATION); } @Override public void showErrorConnectingDeviceNotification(Device device) { showNotification( "Unable to connect to device '" + device.getName() + "'. Make sure that your computer and your " + "device are connected to the same WiFi network.", NotificationType.INFORMATION); } @Override public void showErrorDisconnectingDeviceNotification(Device device) { showNotification( "Unable to disconnect device '" + device.getName() + "'. Make sure that your computer and your " + "device are connected to the same WiFi network.", NotificationType.INFORMATION); } @Override public void showADBNotInstalledNotification() { showNotification("'adb' command not found. Review your Android SDK installation.", NotificationType.ERROR); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/view/View.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.view; import com.github.pedrovgs.androidwifiadb.Device; public interface View { void showNoConnectedDevicesNotification(); void showConnectedDeviceNotification(Device device); void showDisconnectedDeviceNotification(Device device); void showErrorConnectingDeviceNotification(Device device); void showErrorDisconnectingDeviceNotification(Device device); void showADBNotInstalledNotification(); } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/ActionButtonListener.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; public interface ActionButtonListener { void onConnectClick(int row); void onDisconnectClick(int row); } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/AndroidDevicesTableModel.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; import com.github.pedrovgs.androidwifiadb.Device; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; public class AndroidDevicesTableModel extends AbstractTableModel { private static final int COLUMN_DEVICE = 0; private static final int COLUMN_STATE = 1; private static final int COLUMN_ACTION = 2; private static final int COLUMN_COUNT = 3; private static final String DEVICE = "Device"; private static final String STATE = "State"; private static final String ACTION = "Action"; private static final String CONNECTED = "Connected"; private static final String DISCONNECTED = "Disconnected"; private final List devices = new ArrayList(); @Override public String getColumnName(int column) { String value = null; switch (column) { case COLUMN_DEVICE: value = DEVICE; break; case COLUMN_STATE: value = STATE; break; case COLUMN_ACTION: value = ACTION; break; default: return value; } return value; } @Override public Class getColumnClass(int columnIndex) { Class value = Object.class; switch (columnIndex) { case COLUMN_DEVICE: value = String.class; break; case COLUMN_STATE: value = String.class; break; default: return value; } return value; } @Override public int getRowCount() { return devices.size(); } @Override public int getColumnCount() { return COLUMN_COUNT; } @Override public Object getValueAt(int rowIndex, int columnIndex) { Device obj = devices.get(rowIndex); Object value = null; switch (columnIndex) { case COLUMN_DEVICE: value = obj.toString(); break; case COLUMN_STATE: value = obj.isConnected() ? CONNECTED : DISCONNECTED; break; case COLUMN_ACTION: break; default: return value; } return value; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == COLUMN_ACTION) { fireTableCellUpdated(rowIndex, columnIndex); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == COLUMN_ACTION; } public void clear() { if (devices != null) { devices.clear(); } } public void add(Device value) { int startIndex = getRowCount(); devices.add(value); fireTableRowsInserted(startIndex, getRowCount() - 1); } public Device get(int index) { if (index >= 0 && index < devices.size()) { return devices.get(index); } return null; } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/AndroidWiFiADBWindow.form ================================================
================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/AndroidWiFiADBWindow.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; import com.github.pedrovgs.androidwifiadb.AndroidWiFiADB; import com.github.pedrovgs.androidwifiadb.Device; import com.github.pedrovgs.androidwifiadb.adb.ADB; import com.github.pedrovgs.androidwifiadb.adb.ADBParser; import com.github.pedrovgs.androidwifiadb.adb.CommandLine; import com.github.pedrovgs.androidwifiadb.view.NotificationView; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentFactory; import java.util.Timer; import java.util.TimerTask; import javax.swing.JPanel; public class AndroidWiFiADBWindow implements ToolWindowFactory, DeviceAction { private static final int INTERVAL_REFRESH_DEVICES = 1000; private final AndroidWiFiADB androidWifiADB; private final CardLayoutDevices cardLayoutDevices; private JPanel toolWindowContent; public AndroidWiFiADBWindow() { CommandLine commandLine = new CommandLine(); ADBParser adbParser = new ADBParser(); ADB adb = new ADB(commandLine, adbParser); this.androidWifiADB = new AndroidWiFiADB(adb, new NotificationView()); cardLayoutDevices = new CardLayoutDevices(toolWindowContent, this); } @Override public void createToolWindowContent(Project project, ToolWindow toolWindow) { androidWifiADB.updateProject(project); createToolWindowContent(toolWindow); setupUI(); monitorDevices(); } @Override public void connectDevice(final Device device) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { androidWifiADB.connectDevice(device); updateUi(); } }); } @Override public void disconnectDevice(final Device device) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { androidWifiADB.disconnectDevice(device); updateUi(); } }); } private void createToolWindowContent(ToolWindow toolWindow) { ContentFactory contentFactory = ContentFactory.SERVICE.getInstance(); Content content = contentFactory.createContent(toolWindowContent, "", false); toolWindow.getContentManager().addContent(content); } private void setupUI() { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { cardLayoutDevices.createAndShowGUI(); } }); } private void monitorDevices() { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { new Timer().schedule(new TimerTask() { @Override public void run() { boolean refreshRequired = androidWifiADB.refreshDevicesList(); if (refreshRequired) { updateUi(); } } }, 0, INTERVAL_REFRESH_DEVICES); } }); } private void updateUi() { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { cardLayoutDevices.setDevices(androidWifiADB.getDevices()); cardLayoutDevices.updateUi(); } }); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/CardLayoutDevices.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; import com.github.pedrovgs.androidwifiadb.Device; import com.intellij.ui.table.JBTable; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Container; import java.util.ArrayList; import java.util.Collection; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; public class CardLayoutDevices implements ActionButtonListener { private static final String CARD_DEVICES = "Card with JTable devices"; private static final String CARD_NO_DEVICES = "Card with no devices info"; private static final String NO_DEVICE_CONNECTED = "No devices connected."; private Container parentContainer; private JPanel cards; private JPanel panelNoDevices; private JPanel panelDevices; private JTable tableDevices; private Collection devices; private DeviceAction deviceAction; public CardLayoutDevices(Container parentContainer, DeviceAction action) { this.deviceAction = action; this.parentContainer = parentContainer; this.devices = new ArrayList(); } public void setDevices(Collection devices) { this.devices = devices; } public void createAndShowGUI() { cards = new JPanel(new CardLayout()); createNoDevicesPanel(); createTableDevices(); cards.add(panelDevices, CARD_DEVICES); cards.add(panelNoDevices, CARD_NO_DEVICES); parentContainer.add(cards, BorderLayout.PAGE_START); setupUi(); } public void updateUi() { if (devices != null && !devices.isEmpty()) { showCard(CARD_DEVICES); updateDevicesTable(); } else { showCard(CARD_NO_DEVICES); } } @Override public void onConnectClick(int row) { Device device = getDeviceAt(row); if (device != null) { deviceAction.connectDevice(device); } } @Override public void onDisconnectClick(int row) { Device device = getDeviceAt(row); if (device != null) { deviceAction.disconnectDevice(device); } } private void setupUi() { if (devices != null && !devices.isEmpty()) { showCard(CARD_DEVICES); } else { showCard(CARD_NO_DEVICES); } } private void showCard(String cardName) { CardLayout cardLayout = (CardLayout) cards.getLayout(); cardLayout.show(cards, cardName); } private void createNoDevicesPanel() { panelNoDevices = new JPanel(new BorderLayout()); JLabel labelNoDevices = new JLabel(NO_DEVICE_CONNECTED); labelNoDevices.setHorizontalAlignment(SwingConstants.CENTER); panelNoDevices.add(labelNoDevices); } private void createTableDevices() { AndroidDevicesTableModel model = new AndroidDevicesTableModel(); for (Device device : devices) { model.add(device); } tableDevices = new JBTable(model); configureTableAppearance(); panelDevices = new JPanel(new BorderLayout()); panelDevices.add(tableDevices.getTableHeader(), BorderLayout.NORTH); panelDevices.add(tableDevices, BorderLayout.CENTER); } private void configureTableAppearance() { tableDevices.setOpaque(false); ((DefaultTableCellRenderer) tableDevices.getDefaultRenderer(Object.class)).setOpaque(false); tableDevices.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); tableDevices.getColumnModel().getColumn(0).setPreferredWidth(100); tableDevices.getColumnModel().getColumn(1).setMinWidth(85); tableDevices.getColumnModel().getColumn(1).setMaxWidth(85); tableDevices.getColumnModel().getColumn(2).setMinWidth(215); tableDevices.getColumnModel().getColumn(2).setMaxWidth(215); tableDevices.getColumnModel().getColumn(2).setCellRenderer(new ConnectDisconnectRenderer()); tableDevices.getColumnModel() .getColumn(2) .setCellEditor(new ConnectDisconnectEditor(new JCheckBox(), this)); } private void updateDevicesTable() { AndroidDevicesTableModel model = (AndroidDevicesTableModel) tableDevices.getModel(); model.clear(); for (Device device : devices) { model.add(device); } tableDevices.setModel(model); model.fireTableDataChanged(); } private Device getDeviceAt(int row) { AndroidDevicesTableModel model = (AndroidDevicesTableModel) tableDevices.getModel(); return model.get(row); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/ConnectDisconnectEditor.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultCellEditor; import javax.swing.JCheckBox; import javax.swing.JTable; public class ConnectDisconnectEditor extends DefaultCellEditor { private boolean clicked; private String clickedButtonAction; private int row, col; private ConnectDisconnectPanel buttonsPanel; private ActionButtonListener listener; public ConnectDisconnectEditor(JCheckBox checkBox, ActionButtonListener listener) { super(checkBox); this.listener = listener; buttonsPanel = new ConnectDisconnectPanel(); buttonsPanel.addActionListeners(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clickedButtonAction = e.getActionCommand(); fireEditingStopped(); } }); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { this.row = row; this.col = column; clicked = true; return buttonsPanel; } @Override public Object getCellEditorValue() { if (clicked && listener != null) { if (ConnectDisconnectPanel.ACTION_CONNECT.equals(clickedButtonAction)) { listener.onConnectClick(row); } else if (ConnectDisconnectPanel.ACTION_DISCONNECT.equals(clickedButtonAction)) { listener.onDisconnectClick(row); } } clickedButtonAction = ""; clicked = false; return ""; } @Override public boolean stopCellEditing() { clicked = false; return super.stopCellEditing(); } @Override protected void fireEditingStopped() { super.fireEditingStopped(); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/ConnectDisconnectPanel.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; import java.awt.GridBagLayout; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; public class ConnectDisconnectPanel extends JPanel { public static final String ACTION_CONNECT = "Connect"; public static final String ACTION_DISCONNECT = "Disconnect"; private JButton connect; private JButton disconnect; public ConnectDisconnectPanel() { setLayout(new GridBagLayout()); setOpaque(false); connect = new JButton(ACTION_CONNECT); connect.setActionCommand(ACTION_CONNECT); connect.setOpaque(false); disconnect = new JButton(ACTION_DISCONNECT); disconnect.setActionCommand(ACTION_DISCONNECT); disconnect.setOpaque(false); add(connect); add(disconnect); } public void addActionListeners(ActionListener listener) { connect.addActionListener(listener); disconnect.addActionListener(listener); } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/ConnectDisconnectRenderer.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; import java.awt.Component; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; public class ConnectDisconnectRenderer extends JPanel implements TableCellRenderer { private final ConnectDisconnectPanel connectDisconnectPane = new ConnectDisconnectPanel(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { connectDisconnectPane.setBackground(table.getSelectionBackground()); } else { connectDisconnectPane.setBackground(table.getBackground()); } return connectDisconnectPane; } } ================================================ FILE: src/main/java/com/github/pedrovgs/androidwifiadb/window/DeviceAction.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.window; import com.github.pedrovgs.androidwifiadb.Device; public interface DeviceAction { void connectDevice(Device device); void disconnectDevice(Device device); } ================================================ FILE: src/main/resources/META-INF/plugin.xml ================================================ com.github.pedrovgs.androidwifiadb Android WiFi ADB 2.5-SNAPSHOT Pedro Vicente Gomez Sanchez Connect your device using a USB cable and press the Android WiFi ADB button. Once the device be connected over WiFi you'll see an IntelliJ/Android Studio notification. Now you can disconnect your USB cable and enjoy deploying, running and debugging your applications over WiFi.
The version 2.0 enables a window to check which of your devices are connected or not and connect/disconnect it manually if needed. ]]>
2.3: Update the main action configuration to be shown in the NavBarToolBar and also in the MainToolBar if the first on is disabled.
2.2: Update error message shown when the device is not properly connected.
2.1: Fix bug associated to some device installations where the adb installation was not recognized.
2.0: Add a new Android WiFi ADB control panel showing all the devices connected by USB to be able to connect/disconnect devices individually.
1.2: Remove the usage of the ANDROID_HOME environment variable. This variable is not needed now.
1.1: Fixes for Windows and Linux.
1.0: Initial version.
]]>
org.jetbrains.android
================================================ FILE: src/test/java/com/github/pedrovgs/androidwifiadb/AndroidWiFiADBTest.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb; import com.github.pedrovgs.androidwifiadb.adb.ADB; import com.github.pedrovgs.androidwifiadb.view.View; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.mockito.Mock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class AndroidWiFiADBTest extends UnitTest { private static final int SOME_DEVICES = 4; private static final String ANY_DEVICE_NAME = "Device nº "; private static final String ANY_DEVICE_ID = "abcdef123"; private static final String ANY_DEVICE_IP = "0.0.0.0"; @Mock private ADB adb; @Mock private View view; @Test public void shouldShowErrorIfADBIsNotInstalled() { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); givenADBIsNotInstalled(); androidWiFiAdb.connectDevices(); verify(view).showADBNotInstalledNotification(); } @Test public void shouldShowNoConnectedDevicesNotificationIfThereAreNotConnectedDevicesByUSB() { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); givenThereAreNoConnectedDevices(); androidWiFiAdb.connectDevices(); verify(view).showNoConnectedDevicesNotification(); } @Test public void shouldShowDevicesConnectedIfADBWiFiWhenConnectionIsEstablished() { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); List devices = givenThereAreSomeDevicesConnectedByUSB(); givenDevicesAreConnectedSuccessfully(devices); androidWiFiAdb.connectDevices(); for (Device device : devices) { verify(view).showConnectedDeviceNotification(device); } } @Test public void shouldShowDeviceConnectionErrorWhenConnectionIsNotEstablished() { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); List devices = givenThereAreSomeDevicesConnectedByUSB(); givenDevicesAreNotConnectedSuccessfully(devices); androidWiFiAdb.connectDevices(); for (Device device : devices) { verify(view).showErrorConnectingDeviceNotification(device); } } @Test public void shouldNotRefreshDevicesListIfAdbIsNotIstalled() throws Exception { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); givenADBIsNotInstalled(); assertFalse(androidWiFiAdb.refreshDevicesList()); } @Test public void shouldRefreshDevicesListAddNewDevice() throws Exception { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); List devices = givenThereAreSomeDevicesConnectedByUSB(); givenDevicesAreConnectedSuccessfully(devices); givenAnyIpToDevices(); assertEquals(0, androidWiFiAdb.getDevices().size()); androidWiFiAdb.refreshDevicesList(); assertEquals(devices.size(), androidWiFiAdb.getDevices().size()); } @Test public void shouldRefreshDevicesListUpdateExistingDevices() throws Exception { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); List devices = givenThereAreSomeDevicesConnectedByUSB(); givenDevicesAreConnectedSuccessfully(devices); androidWiFiAdb.connectDevices(); androidWiFiAdb.refreshDevicesList(); assertEquals(devices.size(), androidWiFiAdb.getDevices().size()); } @Test public void shouldDisconnectDevice() throws Exception { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); givenADBIsInstalled(); Device device = givenAnyConnectedDevice(); givenDevicesAreDisconnectedSuccessfully(Arrays.asList(device)); androidWiFiAdb.disconnectDevice(device); assertFalse(device.isConnected()); } @Test public void shouldConnectDevice() throws Exception { AndroidWiFiADB androidWiFiAdb = givenAnAndroidWiFiADB(); givenADBIsInstalled(); Device device = givenAnyDisonnectedDevice(); givenDevicesAreConnectedSuccessfully(Arrays.asList(device)); androidWiFiAdb.connectDevice(device); assertTrue(device.isConnected()); } private Device givenAnyConnectedDevice() { Device device = new Device(ANY_DEVICE_NAME, ANY_DEVICE_ID); device.setConnected(true); return device; } private Device givenAnyDisonnectedDevice() { return new Device(ANY_DEVICE_NAME, ANY_DEVICE_ID); } private void givenDevicesAreNotConnectedSuccessfully(List devices) { for (Device device : devices) { device.setConnected(false); } when(adb.getDevicesConnectedByUSB()).thenReturn(devices); when(adb.connectDevices(devices)).thenReturn(devices); } private void givenDevicesAreConnectedSuccessfully(List devices) { for (Device device : devices) { device.setConnected(true); } when(adb.getDevicesConnectedByUSB()).thenReturn(devices); when(adb.connectDevices(devices)).thenReturn(new ArrayList(devices)); } private void givenDevicesAreDisconnectedSuccessfully(final List devices) { for (Device device : devices) { device.setConnected(false); } when(adb.disconnectDevices(devices)).thenReturn(devices); } private List givenThereAreSomeDevicesConnectedByUSB() { when(adb.isInstalled()).thenReturn(true); return getSomeDevices(SOME_DEVICES); } private List getSomeDevices(int devicesCount) { List devices = new LinkedList(); for (int i = 0; i < devicesCount; i++) { String name = ANY_DEVICE_NAME + i; String id = String.valueOf(i); Device device = new Device(name, id); devices.add(device); } return devices; } private void givenThereAreNoConnectedDevices() { when(adb.isInstalled()).thenReturn(true); when(adb.getDevicesConnectedByUSB()).thenReturn(new LinkedList()); } private void givenADBIsNotInstalled() { when(adb.isInstalled()).thenReturn(false); } private void givenADBIsInstalled() { when(adb.isInstalled()).thenReturn(true); } private void givenAnyIpToDevices() { when(adb.getDeviceIp((Device) anyObject())).thenReturn(ANY_DEVICE_IP); } private AndroidWiFiADB givenAnAndroidWiFiADB() { return new AndroidWiFiADB(adb, view); } } ================================================ FILE: src/test/java/com/github/pedrovgs/androidwifiadb/UnitTest.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb; import org.junit.Before; import org.mockito.MockitoAnnotations; public class UnitTest { @Before public void setUp() { MockitoAnnotations.initMocks(this); } } ================================================ FILE: src/test/java/com/github/pedrovgs/androidwifiadb/adb/ADBParserTest.java ================================================ /* * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.androidwifiadb.adb; import com.github.pedrovgs.androidwifiadb.Device; import com.github.pedrovgs.androidwifiadb.UnitTest; import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ADBParserTest extends UnitTest { private static final String ADB_DEVICES_OUTPUT_ONE_DEVICE = "List of devices attached\n" + "0810a0dd00e3656f device usb:336592896X product:hammerhead model:Nexus_5 device:hammerhead"; private static final String ADB_DEVICES_OUTPUT_SOME_DEVICES = "List of devices attached\n" + "0810a0dd00e3656f device usb:336592896X product:hammerhead model:Nexus_5 device:hammerhead\n" + "0810a0d333333656f device usb:336592896X product:hammerhead model:Nexus_6"; private static final String ADB_DEVICES_NO_DEVICES = "List of devices attached\n"; private static final String ADB_DEVICES_OUTPUT_WITH_DEVICES_BY_IP = "List of devices attached\n" + "0810a0dd00e3656f device usb:336592896X product:hammerhead model:Nexus_5 device:hammerhead\n" + "192.168.1.128:5555f device usb:336592896X product:hammerhead model:Nexus_6 device:hammerhead\n"; private static final String GET_IP_OUTPUT = "21: wlan0: mtu 1500 qdisc pfifo_fast state UP qlen 1000\n" + " inet 192.168.1.128/24 brd 192.168.1.255 scope global wlan0"; private static final String GET_ADB_PROP_DEVICE_NOT_FOUND = "error: device '(null)' not found"; private static final String GET_ADP_PROP_NO_TCP_PORT_INFO = "[init.svc.adbd]: [running]\n" + "[persist.sys.usb.config]: [mtp,adb]\n" + "[ro.adb.secure]: [1]\n" + "[sys.usb.config]: [mtp,adb]\n" + "[sys.usb.state]: [mtp,adb]"; private static final String TCPIP_PORT = "5555"; private static final String GET_ADB_PROP_WITH_TCP_PORT = " [init.svc.adbd]: [running]\n" + " [persist.sys.usb.config]: [mtp,adb]\n" + " [ro.adb.secure]: [1]\n" + " [service.adb.tcp.port]: [" + TCPIP_PORT + "]\n" + " [sys.usb.config]: [mtp,adb]\n" + " [sys.usb.state]: [mtp,adb]\n"; @Test public void shouldParseAdbDevicesOutputAndReturnTheListOfDevicesWithJustOneDeviceConnected() { ADBParser parser = givenAADBParser(); List devices = parser.parseGetDevicesOutput(ADB_DEVICES_OUTPUT_ONE_DEVICE); assertEquals(1, devices.size()); Device device = devices.get(0); assertEquals("0810a0dd00e3656f", device.getId()); assertEquals("Nexus_5", device.getName()); } @Test public void shouldParseAdbDevicesOutputAndReturnTheListOfDevicesWithMoreThanOneDevice() { ADBParser parser = givenAADBParser(); List devices = parser.parseGetDevicesOutput(ADB_DEVICES_OUTPUT_SOME_DEVICES); assertEquals(2, devices.size()); Device firstDevice = devices.get(0); Device secondDevice = devices.get(1); assertEquals("0810a0dd00e3656f", firstDevice.getId()); assertEquals("Nexus_5", firstDevice.getName()); assertEquals("0810a0d333333656f", secondDevice.getId()); assertEquals("Nexus_6", secondDevice.getName()); } @Test public void shouldReturnAnEmptyListIfThereAreNoDevices() { ADBParser parser = givenAADBParser(); List devices = parser.parseGetDevicesOutput(ADB_DEVICES_NO_DEVICES); assertTrue(devices.isEmpty()); } @Test public void shouldNotReturnDevicesConnectedByIp() { ADBParser parser = givenAADBParser(); List devices = parser.parseGetDevicesOutput(ADB_DEVICES_OUTPUT_WITH_DEVICES_BY_IP); assertEquals(1, devices.size()); Device device = devices.get(0); assertEquals("0810a0dd00e3656f", device.getId()); assertEquals("Nexus_5", device.getName()); } @Test public void shouldReturnDeviceIp() { ADBParser parser = givenAADBParser(); String deviceIp = parser.parseGetDeviceIp(GET_IP_OUTPUT); assertEquals("192.168.1.128", deviceIp); } @Test public void shouldReturnEmptyIfDeviceIpIsAnEmptyString() { ADBParser parser = givenAADBParser(); String deviceIp = parser.parseGetDeviceIp(""); assertEquals("", deviceIp); } @Test public void shouldReturnEmptyStringIfDeviceNotFound() throws Exception { ADBParser parser = givenAADBParser(); String tcpPort = parser.parseAdbServiceTcpPort(GET_ADB_PROP_DEVICE_NOT_FOUND); assertEquals("", tcpPort); } @Test public void shouldReturnEmptyStringIfAdbPropertiesDoesNotContainTCPPort() throws Exception { ADBParser parser = givenAADBParser(); String tcpPort = parser.parseAdbServiceTcpPort(GET_ADP_PROP_NO_TCP_PORT_INFO); assertEquals("", tcpPort); } @Test public void shouldReturnTCPPort() throws Exception { ADBParser parser = givenAADBParser(); String tcpPort = parser.parseAdbServiceTcpPort(GET_ADB_PROP_WITH_TCP_PORT); assertEquals(TCPIP_PORT, tcpPort); } private ADBParser givenAADBParser() { return new ADBParser(); } } ================================================ FILE: src/test/java/com/github/pedrovgs/androidwifiadb/window/AndroidDevicesTableModelTest.java ================================================ /* * * * Copyright (C) 2015 Pedro Vicente Gómez Sánchez. * * * * 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.github.pedrovgs.androidwifiadb.window; import com.github.pedrovgs.androidwifiadb.Device; import com.github.pedrovgs.androidwifiadb.UnitTest; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import org.junit.Test; import org.mockito.Mock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; public class AndroidDevicesTableModelTest extends UnitTest { private static final int COLUMN_DEVICE = 0; private static final int COLUMN_STATE = 1; private static final int COLUMN_ACTION = 2; private static final int COLUMN_WITH_NOT_VALID_INDEX = -1; private static final String ANY_DEVICE_ID = "abcdef"; private static final String ANY_DEVICE_NAME = "test_name"; private static final String CONNECTED = "Connected"; private static final String DISCONNECTED = "Disconnected"; @Mock TableModelListener tableModelListener; @Test public void shouldAddDevice() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); assertNull(androidDevicesTableModel.get(0)); Device device = givenAnyDevice(); androidDevicesTableModel.add(device); assertEquals(device, androidDevicesTableModel.get(0)); } @Test public void shouldClearDevicesList() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); androidDevicesTableModel.add(givenAnyDevice()); assertEquals(1, androidDevicesTableModel.getRowCount()); androidDevicesTableModel.clear(); assertEquals(0, androidDevicesTableModel.getRowCount()); } @Test public void shouldReturnValueDeviceAsStringForDeviceColumn() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); Device device = givenAnyDevice(); androidDevicesTableModel.add(device); assertEquals(device.toString(), androidDevicesTableModel.getValueAt(0, COLUMN_DEVICE)); } @Test public void shouldReturnValueConnectedStringForConnectedDevice() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); Device device = givenAnyDevice(); device.setConnected(true); androidDevicesTableModel.add(device); assertEquals(CONNECTED, androidDevicesTableModel.getValueAt(0, COLUMN_STATE)); } @Test public void shouldReturnValueDisconnectedStringForDisconnectedDevice() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); Device device = givenAnyDevice(); device.setConnected(false); androidDevicesTableModel.add(device); assertEquals(DISCONNECTED, androidDevicesTableModel.getValueAt(0, COLUMN_STATE)); } @Test public void shouldReturnNullValueForActionColumn() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); androidDevicesTableModel.add(givenAnyDevice()); assertEquals(null, androidDevicesTableModel.getValueAt(0, COLUMN_ACTION)); } @Test public void shouldReturnNullValueForUnknownColumn() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); androidDevicesTableModel.add(givenAnyDevice()); assertEquals(null, androidDevicesTableModel.getValueAt(0, COLUMN_WITH_NOT_VALID_INDEX)); } @Test public void shouldReturnEditableCellForActionColumn() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); androidDevicesTableModel.add(givenAnyDevice()); assertFalse(androidDevicesTableModel.isCellEditable(0, COLUMN_STATE) || androidDevicesTableModel.isCellEditable(0, COLUMN_DEVICE)); assertTrue(androidDevicesTableModel.isCellEditable(0, COLUMN_ACTION)); } @Test public void shouldFireCellUpdateOnlyForActionColumn() throws Exception { AndroidDevicesTableModel androidDevicesTableModel = givenEmptyDevicesTableModel(); androidDevicesTableModel.addTableModelListener(tableModelListener); androidDevicesTableModel.setValueAt(anyObject(), 0, COLUMN_ACTION); verify(tableModelListener, atLeastOnce()).tableChanged((TableModelEvent) anyObject()); } private Device givenAnyDevice() { return new Device(ANY_DEVICE_NAME, ANY_DEVICE_ID); } private AndroidDevicesTableModel givenEmptyDevicesTableModel() { return new AndroidDevicesTableModel(); } }