Merge pull request #94 from janosvitok/cleanup

Cleanup
This commit is contained in:
Samuel Carlsson 2018-09-10 21:21:02 +02:00 committed by GitHub
commit 6c84fe6542
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 61 additions and 91 deletions

View File

@ -1,6 +1,6 @@
# Contributing # # Contributing #
## Why contributing? ## ## Why contributing? ##
The original author and all users of this library are very greatful for your contribution The original author and all users of this library are very grateful for your contribution
to this Open Source Project. Also most employers value people active in the Open Source to this Open Source Project. Also most employers value people active in the Open Source
community. community.
@ -25,4 +25,4 @@ your proposed change meets, or exceeds, the quality of the jadb source code.
full terse. full terse.
* Newline at end of file - This makes `cat`-ing files, etc easier. * Newline at end of file - This makes `cat`-ing files, etc easier.
Happy coding! I, the original author, and all users are greatful for your contribution. :-) Happy coding! I, the original author, and all users are grateful for your contribution. :-)

View File

@ -44,7 +44,7 @@ An overview of the protocol can be found here: [Overview](https://android.google
A list of the available commands that a ADB Server may accept can be found here: A list of the available commands that a ADB Server may accept can be found here:
[Services](https://android.googlesource.com/platform/system/adb/+/master/SERVICES.TXT) [Services](https://android.googlesource.com/platform/system/adb/+/master/SERVICES.TXT)
The description for the protocol for transfering files can be found here: [SYNC.TXT](https://android.googlesource.com/platform/system/adb/+/master/SYNC.TXT). The description for the protocol for transferring files can be found here: [SYNC.TXT](https://android.googlesource.com/platform/system/adb/+/master/SYNC.TXT).
## Using JADB in your application ## ## Using JADB in your application ##

View File

@ -3,7 +3,7 @@ package se.vidstige.jadb;
import java.util.List; import java.util.List;
public interface DeviceDetectionListener { public interface DeviceDetectionListener {
public void onDetect(List<JadbDevice> devices); void onDetect(List<JadbDevice> devices);
public void onException(Exception e); void onException(Exception e);
} }

View File

@ -61,7 +61,7 @@ public class HostConnectionCommand {
private String extractError(String response) { private String extractError(String response) {
int lastColon = response.lastIndexOf(':'); int lastColon = response.lastIndexOf(':');
if (lastColon != -1) { if (lastColon != -1) {
return response.substring(lastColon, response.length()); return response.substring(lastColon);
} else { } else {
return response; return response;
} }

View File

@ -6,5 +6,5 @@ import java.io.IOException;
* Created by Törcsi on 2016. 03. 01.. * Created by Törcsi on 2016. 03. 01..
*/ */
public interface ITransportFactory { public interface ITransportFactory {
public Transport createTransport() throws IOException; Transport createTransport() throws IOException;
} }

View File

@ -78,7 +78,7 @@ public class JadbConnection implements ITransportFactory {
for (String line : lines) { for (String line : lines) {
String[] parts = line.split("\t"); String[] parts = line.split("\t");
if (parts.length > 1) { if (parts.length > 1) {
devices.add(new JadbDevice(parts[0], parts[1], this)); devices.add(new JadbDevice(parts[0], this)); // parts[1] is type
} }
} }
return devices; return devices;

View File

@ -16,10 +16,12 @@ public class JadbDevice {
BootLoader BootLoader
} }
//noinspection OctalInteger
private static final int DEFAULT_MODE = 0664;
private final String serial; private final String serial;
private final ITransportFactory transportFactory; private final ITransportFactory transportFactory;
JadbDevice(String serial, String type, ITransportFactory tFactory) { JadbDevice(String serial, ITransportFactory tFactory) {
this.serial = serial; this.serial = serial;
this.transportFactory = tFactory; this.transportFactory = tFactory;
} }
@ -45,13 +47,7 @@ public class JadbDevice {
private Transport getTransport() throws IOException, JadbException { private Transport getTransport() throws IOException, JadbException {
Transport transport = transportFactory.createTransport(); Transport transport = transportFactory.createTransport();
if (serial == null) { send(transport, serial == null ? "host:transport-any" : "host:transport:" + serial );
transport.send("host:transport-any");
transport.verifyResponse();
} else {
transport.send("host:transport:" + serial);
transport.verifyResponse();
}
return transport; return transport;
} }
@ -61,13 +57,7 @@ public class JadbDevice {
public State getState() throws IOException, JadbException { public State getState() throws IOException, JadbException {
Transport transport = transportFactory.createTransport(); Transport transport = transportFactory.createTransport();
if (serial == null) { send(transport, serial == null ? "host:get-state" : "host-serial:" + serial + ":get-state");
transport.send("host:get-state");
transport.verifyResponse();
} else {
transport.send("host-serial:" + serial + ":get-state");
transport.verifyResponse();
}
State state = convertState(transport.readString()); State state = convertState(transport.readString());
transport.close(); transport.close();
@ -158,11 +148,6 @@ public class JadbDevice {
return result; return result;
} }
private int getMode(File file) {
//noinspection OctalInteger
return 0664;
}
public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException { public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException {
Transport transport = getTransport(); Transport transport = getTransport();
SyncTransport sync = transport.startSync(); SyncTransport sync = transport.startSync();
@ -175,9 +160,9 @@ public class JadbDevice {
} }
public void push(File local, RemoteFile remote) throws IOException, JadbException { public void push(File local, RemoteFile remote) throws IOException, JadbException {
FileInputStream fileStream = new FileInputStream(local); try (FileInputStream fileStream = new FileInputStream(local)) {
push(fileStream, local.lastModified(), getMode(local), remote); push(fileStream, local.lastModified(), DEFAULT_MODE, remote);
fileStream.close(); }
} }
public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException { public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException {
@ -189,9 +174,9 @@ public class JadbDevice {
} }
public void pull(RemoteFile remote, File local) throws IOException, JadbException { public void pull(RemoteFile remote, File local) throws IOException, JadbException {
FileOutputStream fileStream = new FileOutputStream(local); try (FileOutputStream fileStream = new FileOutputStream(local)) {
pull(remote, fileStream); pull(remote, fileStream);
fileStream.close(); }
} }
private void send(Transport transport, String command) throws IOException, JadbException { private void send(Transport transport, String command) throws IOException, JadbException {
@ -222,10 +207,8 @@ public class JadbDevice {
return false; return false;
JadbDevice other = (JadbDevice) obj; JadbDevice other = (JadbDevice) obj;
if (serial == null) { if (serial == null) {
if (other.serial != null) return other.serial == null;
return false; }
} else if (!serial.equals(other.serial)) return serial.equals(other.serial);
return false;
return true;
} }
} }

View File

@ -1,7 +1,7 @@
package se.vidstige.jadb; package se.vidstige.jadb;
import java.io.*; import java.io.*;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
/** /**
* Created by vidstige on 2014-03-19. * Created by vidstige on 2014-03-19.
@ -52,7 +52,7 @@ public class SyncTransport {
public String readString(int length) throws IOException { public String readString(int length) throws IOException {
byte[] buffer = new byte[length]; byte[] buffer = new byte[length];
input.readFully(buffer); input.readFully(buffer);
return new String(buffer, Charset.forName("utf-8")); return new String(buffer, StandardCharsets.UTF_8);
} }
public RemoteFileRecord readDirectoryEntry() throws IOException { public RemoteFileRecord readDirectoryEntry() throws IOException {

View File

@ -2,7 +2,7 @@ package se.vidstige.jadb;
import java.io.*; import java.io.*;
import java.net.Socket; import java.net.Socket;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
class Transport { class Transport {
@ -44,7 +44,7 @@ class Transport {
DataInput reader = new DataInputStream(inputStream); DataInput reader = new DataInputStream(inputStream);
byte[] responseBuffer = new byte[length]; byte[] responseBuffer = new byte[length];
reader.readFully(responseBuffer); reader.readFully(responseBuffer);
return new String(responseBuffer, Charset.forName("utf-8")); return new String(responseBuffer, StandardCharsets.UTF_8);
} }
public String getCommandLength(String command) { public String getCommandLength(String command) {
@ -52,7 +52,7 @@ class Transport {
} }
public void send(String command) throws IOException { public void send(String command) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outputStream); OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
writer.write(getCommandLength(command)); writer.write(getCommandLength(command));
writer.write(command); writer.write(command);
writer.flush(); writer.flush();

View File

@ -55,7 +55,7 @@ public class PackageManager {
arguments.add("install"); arguments.add("install");
arguments.addAll(extraArguments); arguments.addAll(extraArguments);
arguments.add(remote.getPath()); arguments.add(remote.getPath());
InputStream s = device.executeShell("pm", arguments.toArray(new String[arguments.size()])); InputStream s = device.executeShell("pm", arguments.toArray(new String[0]));
String result = Stream.readAll(s, StandardCharsets.UTF_8); String result = Stream.readAll(s, StandardCharsets.UTF_8);
remove(remote); remove(remote);
verifyOperation("install", apkFile.getName(), result); verifyOperation("install", apkFile.getName(), result);

View File

@ -6,6 +6,7 @@ import se.vidstige.jadb.JadbException;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -15,7 +16,7 @@ import java.util.regex.Pattern;
* A class which works with properties, uses getprop and setprop methods of android shell * A class which works with properties, uses getprop and setprop methods of android shell
*/ */
public class PropertyManager { public class PropertyManager {
private final Pattern pattern = Pattern.compile("^\\[([a-zA-Z0-9_.-]*)\\]:.\\[([^\\[\\]]*)\\]"); private final Pattern pattern = Pattern.compile("^\\[([a-zA-Z0-9_.-]*)]:.\\[([^\\[\\]]*)]");
private final JadbDevice device; private final JadbDevice device;
public PropertyManager(JadbDevice device) { public PropertyManager(JadbDevice device) {
@ -24,7 +25,7 @@ public class PropertyManager {
public Map<String, String> getprop() throws IOException, JadbException { public Map<String, String> getprop() throws IOException, JadbException {
try (BufferedReader bufferedReader = try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(device.executeShell("getprop")))) { new BufferedReader(new InputStreamReader(device.executeShell("getprop"), StandardCharsets.UTF_8))) {
return parseProp(bufferedReader); return parseProp(bufferedReader);
} }
} }

View File

@ -41,6 +41,7 @@ class AdbProtocolHandler implements Runnable {
DataInputStream input = new DataInputStream(socket.getInputStream()); DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream()) DataOutputStream output = new DataOutputStream(socket.getOutputStream())
) { ) {
//noinspection StatementWithEmptyBody
while (processCommand(input, output)) { while (processCommand(input, output)) {
// nothing to do here // nothing to do here
} }
@ -80,7 +81,7 @@ class AdbProtocolHandler implements Runnable {
return true; return true;
} }
private void hostSerial(DataOutputStream output, String command) throws IOException { private void hostSerial(DataOutput output, String command) throws IOException {
String[] strs = command.split(":",0); String[] strs = command.split(":",0);
if (strs.length != 3) { if (strs.length != 3) {
throw new ProtocolException("Invalid command: " + command); throw new ProtocolException("Invalid command: " + command);
@ -102,7 +103,7 @@ class AdbProtocolHandler implements Runnable {
} }
} }
private void hostGetState(DataOutputStream output) throws IOException { private void hostGetState(DataOutput output) throws IOException {
// TODO: Check so that exactly one device is selected. // TODO: Check so that exactly one device is selected.
AdbDeviceResponder device = responder.getDevices().get(0); AdbDeviceResponder device = responder.getDevices().get(0);
output.writeBytes("OKAY"); output.writeBytes("OKAY");
@ -115,13 +116,13 @@ class AdbProtocolHandler implements Runnable {
shell(shellCommand, output, input); shell(shellCommand, output, input);
} }
private void hostTransport(DataOutputStream output, String command) throws IOException { private void hostTransport(DataOutput output, String command) throws IOException {
String serial = command.substring("host:transport:".length()); String serial = command.substring("host:transport:".length());
selected = findDevice(serial); selected = findDevice(serial);
output.writeBytes("OKAY"); output.writeBytes("OKAY");
} }
private void hostDevices(DataOutputStream output) throws IOException { private void hostDevices(DataOutput output) throws IOException {
ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ByteArrayOutputStream tmp = new ByteArrayOutputStream();
DataOutputStream writer = new DataOutputStream(tmp); DataOutputStream writer = new DataOutputStream(tmp);
for (AdbDeviceResponder d : responder.getDevices()) { for (AdbDeviceResponder d : responder.getDevices()) {
@ -131,13 +132,13 @@ class AdbProtocolHandler implements Runnable {
send(output, new String(tmp.toByteArray(), StandardCharsets.UTF_8)); send(output, new String(tmp.toByteArray(), StandardCharsets.UTF_8));
} }
private void hostTransportAny(DataOutputStream output) throws IOException { private void hostTransportAny(DataOutput output) throws IOException {
// TODO: Check so that exactly one device is selected. // TODO: Check so that exactly one device is selected.
selected = responder.getDevices().get(0); selected = responder.getDevices().get(0);
output.writeBytes("OKAY"); output.writeBytes("OKAY");
} }
private void hostVersion(DataOutputStream output) throws IOException { private void hostVersion(DataOutput output) throws IOException {
output.writeBytes("OKAY"); output.writeBytes("OKAY");
send(output, String.format("%04x", responder.getVersion())); send(output, String.format("%04x", responder.getVersion()));
} }

View File

@ -11,7 +11,7 @@ import java.io.DataInput;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -20,7 +20,7 @@ import java.util.List;
*/ */
public class FakeAdbServer implements AdbResponder { public class FakeAdbServer implements AdbResponder {
private final AdbServer server; private final AdbServer server;
private final List<DeviceResponder> devices = new ArrayList<DeviceResponder>(); private final List<DeviceResponder> devices = new ArrayList<>();
public FakeAdbServer(int port) { public FakeAdbServer(int port) {
server = new AdbServer(this, port); server = new AdbServer(this, port);
@ -91,11 +91,11 @@ public class FakeAdbServer implements AdbResponder {
return new ArrayList<AdbDeviceResponder>(devices); return new ArrayList<AdbDeviceResponder>(devices);
} }
private class DeviceResponder implements AdbDeviceResponder { private static class DeviceResponder implements AdbDeviceResponder {
private final String serial; private final String serial;
private final String type; private final String type;
private List<FileExpectation> fileExpectations = new ArrayList<FileExpectation>(); private List<FileExpectation> fileExpectations = new ArrayList<>();
private List<ShellExpectation> shellExpectations = new ArrayList<ShellExpectation>(); private List<ShellExpectation> shellExpectations = new ArrayList<>();
private DeviceResponder(String serial, String type) { private DeviceResponder(String serial, String type) {
this.serial = serial; this.serial = serial;
@ -155,7 +155,7 @@ public class FakeAdbServer implements AdbResponder {
org.junit.Assert.assertEquals(0, shellExpectations.size()); org.junit.Assert.assertEquals(0, shellExpectations.size());
} }
private class FileExpectation implements ExpectationBuilder { private static class FileExpectation implements ExpectationBuilder {
private final RemoteFile path; private final RemoteFile path;
private byte[] content; private byte[] content;
private String failMessage; private String failMessage;
@ -179,7 +179,7 @@ public class FakeAdbServer implements AdbResponder {
@Override @Override
public void withContent(String content) { public void withContent(String content) {
this.content = content.getBytes(Charset.forName("utf-8")); this.content = content.getBytes(StandardCharsets.UTF_8);
} }
public boolean matches(RemoteFile path) { public boolean matches(RemoteFile path) {
@ -199,7 +199,7 @@ public class FakeAdbServer implements AdbResponder {
} }
} }
public class ShellExpectation { public static class ShellExpectation {
private final String command; private final String command;
private byte[] stdout; private byte[] stdout;
@ -212,7 +212,7 @@ public class FakeAdbServer implements AdbResponder {
} }
public void returns(String stdout) { public void returns(String stdout) {
this.stdout = stdout.getBytes(Charset.forName("utf-8")); this.stdout = stdout.getBytes(StandardCharsets.UTF_8);
} }
public void writeOutputTo(DataOutputStream stdout) throws IOException { public void writeOutputTo(DataOutputStream stdout) throws IOException {

View File

@ -48,7 +48,7 @@ public class FakeSubprocess extends Subprocess {
} }
} }
private class Expectation { private static class Expectation {
private final String[] command; private final String[] command;
private final int exitValue; private final int exitValue;

View File

@ -31,9 +31,7 @@ public class RealDeviceTestCases {
public static void tryToStartAdbServer() { public static void tryToStartAdbServer() {
try { try {
new AdbServerLauncher(new Subprocess(), System.getenv()).launch(); new AdbServerLauncher(new Subprocess(), System.getenv()).launch();
} catch (IOException e) { } catch (IOException | InterruptedException e) {
System.out.println("Could not start adb-server");
} catch (InterruptedException e) {
System.out.println("Could not start adb-server"); System.out.println("Could not start adb-server");
} }
} }
@ -113,13 +111,9 @@ public class RealDeviceTestCases {
@Test @Test
public void testScreenshot() throws Exception { public void testScreenshot() throws Exception {
JadbDevice any = jadb.getAnyDevice(); JadbDevice any = jadb.getAnyDevice();
FileOutputStream outputStream = null; try (FileOutputStream outputStream = new FileOutputStream(temporaryFolder.newFile("screenshot.png"))) {
try {
outputStream = new FileOutputStream(temporaryFolder.newFile("screenshot.png"));
InputStream stdout = any.executeShell("screencap", "-p"); InputStream stdout = any.executeShell("screencap", "-p");
Stream.copy(stdout, outputStream); Stream.copy(stdout, outputStream);
} finally {
if (outputStream != null) outputStream.close();
} }
} }

View File

@ -12,12 +12,9 @@ public class AdbOutputStreamFixture {
private byte[] passthrough(byte[] input) throws IOException { private byte[] passthrough(byte[] input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream();
OutputStream sut = new AdbFilterOutputStream(output); try (OutputStream sut = new AdbFilterOutputStream(output)) {
try { sut.write(input);
sut.write(input); sut.flush();
sut.flush();
} finally {
sut.close();
} }
return output.toByteArray(); return output.toByteArray();
} }

View File

@ -12,7 +12,7 @@ import se.vidstige.jadb.test.fakes.FakeAdbServer;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -72,7 +72,7 @@ public class MockedTestCases {
server.add("serial-123"); server.add("serial-123");
server.expectPush("serial-123", new RemoteFile("/remote/path/abc.txt")).withContent("abc"); server.expectPush("serial-123", new RemoteFile("/remote/path/abc.txt")).withContent("abc");
JadbDevice device = connection.getDevices().get(0); JadbDevice device = connection.getDevices().get(0);
ByteArrayInputStream fileContents = new ByteArrayInputStream("abc".getBytes()); ByteArrayInputStream fileContents = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8));
device.push(fileContents, parseDate("1981-08-25 13:37"), 0666, new RemoteFile("/remote/path/abc.txt")); device.push(fileContents, parseDate("1981-08-25 13:37"), 0666, new RemoteFile("/remote/path/abc.txt"));
} }
@ -81,7 +81,7 @@ public class MockedTestCases {
server.add("serial-123"); server.add("serial-123");
server.expectPush("serial-123", new RemoteFile("/remote/path/abc.txt")).failWith("No such directory"); server.expectPush("serial-123", new RemoteFile("/remote/path/abc.txt")).failWith("No such directory");
JadbDevice device = connection.getDevices().get(0); JadbDevice device = connection.getDevices().get(0);
ByteArrayInputStream fileContents = new ByteArrayInputStream("abc".getBytes()); ByteArrayInputStream fileContents = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8));
device.push(fileContents, parseDate("1981-08-25 13:37"), 0666, new RemoteFile("/remote/path/abc.txt")); device.push(fileContents, parseDate("1981-08-25 13:37"), 0666, new RemoteFile("/remote/path/abc.txt"));
} }
@ -92,7 +92,7 @@ public class MockedTestCases {
JadbDevice device = connection.getDevices().get(0); JadbDevice device = connection.getDevices().get(0);
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream();
device.pull(new RemoteFile("/remote/path/abc.txt"), buffer); device.pull(new RemoteFile("/remote/path/abc.txt"), buffer);
Assert.assertArrayEquals("foobar".getBytes(Charset.forName("utf-8")), buffer.toByteArray()); Assert.assertArrayEquals("foobar".getBytes(StandardCharsets.UTF_8), buffer.toByteArray());
} }
@Test @Test

View File

@ -15,10 +15,9 @@ import java.util.List;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class PackageManagerTest { public class PackageManagerTest {
private final String DEVICE_SERIAL = "serial-123"; private static final String DEVICE_SERIAL = "serial-123";
private FakeAdbServer server; private FakeAdbServer server;
private JadbConnection connection;
private JadbDevice device; private JadbDevice device;
@Before @Before
@ -26,9 +25,7 @@ public class PackageManagerTest {
server = new FakeAdbServer(15037); server = new FakeAdbServer(15037);
server.start(); server.start();
server.add(DEVICE_SERIAL); server.add(DEVICE_SERIAL);
connection = new JadbConnection("localhost", 15037); device = new JadbConnection("localhost", 15037).getDevices().get(0);
device = connection.getDevices().get(0);
} }
@After @After

View File

@ -14,10 +14,9 @@ import java.util.Map;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class PropertyManagerTest { public class PropertyManagerTest {
private final String DEVICE_SERIAL = "serial-123"; private static final String DEVICE_SERIAL = "serial-123";
private FakeAdbServer server; private FakeAdbServer server;
private JadbConnection connection;
private JadbDevice device; private JadbDevice device;
@Before @Before
@ -25,9 +24,7 @@ public class PropertyManagerTest {
server = new FakeAdbServer(15037); server = new FakeAdbServer(15037);
server.start(); server.start();
server.add(DEVICE_SERIAL); server.add(DEVICE_SERIAL);
connection = new JadbConnection("localhost", 15037); device = new JadbConnection("localhost", 15037).getDevices().get(0);
device = connection.getDevices().get(0);
} }
@After @After