com.android.ddmlib.ShellCommandUnresponsiveException Java Examples

The following examples show how to use com.android.ddmlib.ShellCommandUnresponsiveException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AdbShellCommandTaskTest.java    From bundletool with Apache License 2.0 6 votes vote down vote up
@Test
public void commandExecution_ShellCommandUnresponsive() {
  FakeDevice fakeDevice =
      FakeDevice.fromDeviceSpec("id1", DeviceState.ONLINE, lDeviceWithLocales("en-US"));
  fakeDevice.injectShellCommandOutput(
      "getprop",
      () -> {
        throw new ShellCommandUnresponsiveException();
      });

  AdbShellCommandTask task = new AdbShellCommandTask(fakeDevice, "getprop");
  Throwable e = assertThrows(CommandExecutionException.class, () -> task.execute());
  assertThat(e)
      .hasMessageThat()
      .contains("Unresponsive shell command while executing 'adb shell");
  assertThat(e).hasCauseThat().isInstanceOf(ShellCommandUnresponsiveException.class);
}
 
Example #2
Source File: FakeDevice.java    From bundletool with Apache License 2.0 6 votes vote down vote up
@Override
public void executeShellCommand(
    String command,
    IShellOutputReceiver receiver,
    long maxTimeToOutputResponse,
    TimeUnit maxTimeUnits)
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {

  checkState(
      commandInjections.containsKey(command),
      "Command %s not found in command injections.",
      command);
  byte[] data = commandInjections.get(command).onExecute().getBytes(UTF_8);
  receiver.addOutput(data, 0, data.length);
  receiver.flush();
}
 
Example #3
Source File: UserIdHelper.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Integer getUserIdFromConfigurationState(
    IDevice device, ConsolePrinter consolePrinter, BlazeAndroidBinaryRunConfigurationState state)
    throws ExecutionException {
  if (state.useWorkProfileIfPresent()) {
    try {
      Integer userId = getWorkProfileId(device);
      if (userId == null) {
        consolePrinter.stderr(
            "Could not locate work profile on selected device. Launching default user.\n");
      }
      return userId;
    } catch (TimeoutException
        | AdbCommandRejectedException
        | ShellCommandUnresponsiveException
        | IOException e) {
      throw new ExecutionException(e);
    }
  }
  return state.getUserId();
}
 
Example #4
Source File: RealAndroidDevice.java    From buck with Apache License 2.0 5 votes vote down vote up
private void chmod644(Path targetDevicePath)
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
  // The standard Java libraries on Android always create new files un-readable by other users.
  // We use the shell user or root to create these files, so we need to explicitly set the mode
  // to allow the app to read them.  Ideally, the agent would do this automatically, but
  // there's no easy way to do this in Java.  We can drop this if we drop support for the
  // Java agent.
  executeCommandWithErrorChecking("chmod 644 " + targetDevicePath);
}
 
Example #5
Source File: Device.java    From bundletool with Apache License 2.0 5 votes vote down vote up
public abstract void executeShellCommand(
String command,
IShellOutputReceiver receiver,
long maxTimeToOutputResponse,
TimeUnit maxTimeUnits)
throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
    IOException;
 
Example #6
Source File: RealAndroidDevice.java    From buck with Apache License 2.0 5 votes vote down vote up
private void rmFilesWithFlags(String dirPath, Iterable<String> filesToDelete, String flags)
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
  String commandPrefix = String.format("cd %s && rm %s ", dirPath, flags);
  // Add a fudge factor for separators and error checking.
  int overhead = commandPrefix.length() + 100;
  for (List<String> rmArgs : chunkArgs(filesToDelete, MAX_ADB_COMMAND_SIZE - overhead)) {
    String command = commandPrefix + Joiner.on(' ').join(rmArgs);
    LOG.debug("Executing %s", command);
    executeCommandWithErrorChecking(command);
  }
}
 
Example #7
Source File: RealAndroidDevice.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Retrieves external storage location (SD card) from device. */
@Nullable
private String deviceGetExternalStorage()
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
  CollectingOutputReceiver receiver = new CollectingOutputReceiver();
  device.executeShellCommand(
      "echo $EXTERNAL_STORAGE", receiver, GETPROP_TIMEOUT, TimeUnit.MILLISECONDS);
  String value = receiver.getOutput().trim();
  if (value.isEmpty()) {
    return null;
  }
  return value;
}
 
Example #8
Source File: RealAndroidDevice.java    From buck with Apache License 2.0 5 votes vote down vote up
private String executeCommandWithErrorChecking(String command)
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
  CollectingOutputReceiver receiver = new CollectingOutputReceiver();
  device.executeShellCommand(command + ECHO_COMMAND_SUFFIX, receiver);
  return checkReceiverOutput(command, receiver);
}
 
Example #9
Source File: MonkeyTestDevice.java    From Android-Monkey-Adapter with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a cat /data/anr/traces.txt command on the device, and sends the result to a
 * <var>receiver</var>.
 * 
 * @param receiver the {@link IShellOutputReceiver} that will receives the
 *            output of the shell command
 */
public boolean traces(IShellOutputReceiver receiver) {
    boolean result = false;
    try {
        mDevice.executeShellCommand("cat /data/anr/traces.txt", receiver,
                60000);
        result = true;
    } catch (ShellCommandUnresponsiveException mttor) {
        result = true;
    } catch (Exception ex) {
        result = false;
    }
    return result;
}
 
Example #10
Source File: MonkeyTestDevice.java    From Android-Monkey-Adapter with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a bugreport command on the device, and sends the result to a
 * <var>receiver</var>.
 * 
 * @param receiver the {@link IShellOutputReceiver} that will receives the
 *            output of the shell command
 */
public boolean bugreport(IShellOutputReceiver receiver) {
    boolean result = false;
    try {
        mDevice.executeShellCommand("bugreport", receiver,
                60000);
        result = true;
    } catch (ShellCommandUnresponsiveException mttor) {
        result = true;
    } catch (Exception ex) {
        result = false;
    }
    return result;
}
 
Example #11
Source File: MonkeyTestDevice.java    From Android-Monkey-Adapter with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a logcat command on the device, and sends the result to a
 * <var>receiver</var>.
 * 
 * @param receiver the {@link IShellOutputReceiver} that will receives the
 *            output of the shell command
 */
public boolean logcat(IShellOutputReceiver receiver) {
    boolean result = false;
    try {
        mDevice.executeShellCommand("logcat -v threadtime *:V", receiver,
                60000);
        result = true;
    } catch (ShellCommandUnresponsiveException mttor) {
        result = true;
    } catch (Exception ex) {
        result = false;
    }
    return result;
}
 
Example #12
Source File: MonkeyTestDevice.java    From Android-Monkey-Adapter with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a monkey command on the device, and sends the result to a
 * <var>receiver</var>.
 * 
 * @param command the shell command to execute
 * @param receiver the {@link IShellOutputReceiver} that will receives the
 *            output of the shell command
 */
public boolean monkey(String command, IShellOutputReceiver receiver) {
    boolean result = false;
    try {
        mDevice.executeShellCommand(command, receiver, 60000);
        result = true;
    } catch (ShellCommandUnresponsiveException mttor) {
        result = true;
    } catch (Exception ex) {
        result = false;
    }
    return result;
}
 
Example #13
Source File: AdbUtil.java    From ADBWIFI with Apache License 2.0 5 votes vote down vote up
public static boolean isAppInstalled(IDevice device, String packageName) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
    GenericReceiver receiver = new GenericReceiver();
    // "pm list packages com.my.package" will return one line per package installed that corresponds to this package.
    // if this list is empty, we know for sure that the app is not installed
    device.executeShellCommand("pm list packages " + packageName, receiver, 15L, TimeUnit.SECONDS);

    //TODO make sure that it is the exact package name and not a subset.
    // e.g. if our app is called com.example but there is another app called com.example.another.app, it will match and return a false positive
    return !receiver.getAdbOutputLines().isEmpty();
}
 
Example #14
Source File: UserIdHelper.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
public static Integer getWorkProfileId(IDevice device)
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
  CollectingOutputReceiver receiver = new CollectingOutputReceiver();
  device.executeShellCommand("pm list users", receiver);
  String result = receiver.getOutput();
  Matcher matcher = USER_ID_REGEX.matcher(result);
  if (matcher.find()) {
    return Integer.parseInt(matcher.group(1));
  }
  return null;
}
 
Example #15
Source File: DdmlibDevice.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@FormatMethod
private void executeAndPrint(String commandFormat, String... args)
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
  String command = formatCommandWithArgs(commandFormat, args);
  lastOutputLine = null;
  out.println("ADB << " + command);
  // ExecuteShellCommand would only tell us about ADB errors, and NOT the actual shell commands
  // We need another way to check exit values of the commands we run.
  // By adding " && echo OK" we can make sure "OK" is printed if the cmd executed successfully.
  device.executeShellCommand(command + " && echo OK", receiver, timeout, TimeUnit.MILLISECONDS);
  if (!"OK".equals(lastOutputLine)) {
    throw new IOException("ADB command failed.");
  }
}
 
Example #16
Source File: DdmlibDevice.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Override
public void executeShellCommand(
    String command,
    IShellOutputReceiver receiver,
    long maxTimeToOutputResponse,
    TimeUnit maxTimeUnits)
    throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
  device.executeShellCommand(command, receiver, maxTimeToOutputResponse, maxTimeUnits);
}
 
Example #17
Source File: LogReader.java    From NBANDROID-V2 with Apache License 2.0 4 votes vote down vote up
private void reallyStartReading() {
    String lastDeviceSerial = currentDevice != null ? currentDevice.getSerialNumber() : "";
    IDevice[] devs = adb.getDevices();

    // clear the current device, because the device may have gone
    currentDevice = null;

    if (requestedDeviceSerial == null) {
        currentDevice = null;

        // if no device was requested, select the first available
        if (devs != null && devs.length > 0) {
            requestedDeviceSerial = devs[0].getSerialNumber();
        } else {
            // previous device has gone?
            if (lastDeviceSerial.isEmpty() == false) {
                changeSupport.firePropertyChange(PROPERTY_CURRENT_DEVICE, lastDeviceSerial, "");
            }

            // no devices available - announce the current state and stop here
            changeSupport.firePropertyChange(PROPERTY_CURRENT_DEVICE_STATE, null, getCurrentDeviceState());

            return;
        }
    }

    // always select current device by requested serial,
    // because the device object may have changed when was disconnected
    if (devs != null) {
        for (IDevice dev : devs) {
            if (dev.getSerialNumber().equals(requestedDeviceSerial)) {
                currentDevice = dev;
                break;
            }
        }
    }

    // get the serial of the current device (or empty string, if none connected)
    String currentDeviceSerial = currentDevice != null ? currentDevice.getSerialNumber() : "";

    // notify all clients, if the selected device has changed
    if (!lastDeviceSerial.equals(currentDeviceSerial)) {
        changeSupport.firePropertyChange(PROPERTY_CURRENT_DEVICE, lastDeviceSerial, currentDeviceSerial);
    }

    if (currentDevice != null && !currentDevice.isOffline()) {
        stopReading();
        shouldBeReading = true;
        receiver = new LogCatOutputReceiver(currentDevice);
        RP.post(new Runnable() {

            @Override
            public void run() {
                reading = true;

                // announce the new device state
                changeSupport.firePropertyChange(PROPERTY_CURRENT_DEVICE_STATE, null, getCurrentDeviceState());

                IDevice currDevice = currentDevice;
                if (currDevice == null) {
                    return;
                }
                try {
                    currDevice.executeShellCommand("logcat -v long", receiver);
                } catch (TimeoutException | AdbCommandRejectedException | ShellCommandUnresponsiveException | IOException e) {
                    LOG.log(Level.FINE, null, e);
                    reading = false;
                } finally {
                    receiver = null;

                    // announce the new device state
                    changeSupport.firePropertyChange(PROPERTY_CURRENT_DEVICE_STATE, null, getCurrentDeviceState());

                    // when the device has changed, we restart the logging process
                    String serial = currDevice.getSerialNumber();
                    if (!serial.equals(requestedDeviceSerial)) {
                        startReading();
                    }
                }
            }
        });
    }
}
 
Example #18
Source File: RemoteAndroidTestRunner.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run(ITestRunListener... listeners)
        throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException {
    run(Arrays.asList(listeners));
}
 
Example #19
Source File: FakeDevice.java    From bundletool with Apache License 2.0 4 votes vote down vote up
String onExecute()
throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
    IOException;
 
Example #20
Source File: DdmlibDevice.java    From bundletool with Apache License 2.0 4 votes vote down vote up
@Override
public void pushApks(ImmutableList<Path> apks, PushOptions pushOptions) {
  String splitsPath = pushOptions.getDestinationPath();
  checkArgument(!splitsPath.isEmpty(), "Splits path cannot be empty.");

  RemoteCommandExecutor commandExecutor =
      new RemoteCommandExecutor(this, pushOptions.getTimeout().toMillis(), System.err);

  try {
    // There are two different flows, depending on if the path is absolute or not...
    if (!splitsPath.startsWith("/")) {
      // Path is relative, so we're going to try to push it to the app's external dir
      String packageName =
          pushOptions
              .getPackageName()
              .orElseThrow(
                  () ->
                      CommandExecutionException.builder()
                          .withInternalMessage(
                              "PushOptions.packageName must be set for relative paths.")
                          .build());

      splitsPath = joinUnixPaths("/sdcard/Android/data/", packageName, "files", splitsPath);
    }
    // Now the path is absolute. We assume it's pointing to a location writeable by ADB shell.
    // It shouldn't point to app's private directory.

    // Some clean up first. Remove the destination dir if flag is set...
    if (pushOptions.getClearDestinationPath()) {
      commandExecutor.executeAndPrint("rm -rf %s", splitsPath);
    }

    // ... and recreate it, making sure the destination dir is empty.
    // We don't want splits from previous runs in the directory.
    // There isn't a nice way to test if dir is empty in shell, but rmdir will return error
    commandExecutor.executeAndPrint(
        "mkdir -p %s && rmdir %s && mkdir -p %s", splitsPath, splitsPath, splitsPath);

    // Try to push files normally. Will fail if ADB shell doesn't have permission to write.
    for (Path path : apks) {
      device.pushFile(
          path.toFile().getAbsolutePath(),
          joinUnixPaths(splitsPath, path.getFileName().toString()));
      System.err.printf(
          "Pushed \"%s\"%n", joinUnixPaths(splitsPath, path.getFileName().toString()));
    }
  } catch (IOException
      | TimeoutException
      | SyncException
      | AdbCommandRejectedException
      | ShellCommandUnresponsiveException e) {
    throw CommandExecutionException.builder()
        .withCause(e)
        .withInternalMessage(
            "Pushing additional splits for local testing failed. Your app might still have been"
                + " installed correctly, but you won't be able to test dynamic modules.")
        .build();
  }
}
 
Example #21
Source File: IRemoteAndroidTestRunner.java    From javaide with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Execute this test run.
 *
 * @param listeners collection of listeners for test results
 * @throws TimeoutException in case of a timeout on the connection.
 * @throws AdbCommandRejectedException if adb rejects the command
 * @throws ShellCommandUnresponsiveException if the device did not output any test result for
 * a period longer than the max time to output.
 * @throws IOException if connection to device was lost.
 *
 * @see #setMaxtimeToOutputResponse(int)
 */
void run(Collection<ITestRunListener> listeners)
        throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException;
 
Example #22
Source File: IRemoteAndroidTestRunner.java    From javaide with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Execute this test run.
 * <p/>
 * Convenience method for {@link #run(Collection)}.
 *
 * @param listeners listens for test results
 * @throws TimeoutException in case of a timeout on the connection.
 * @throws AdbCommandRejectedException if adb rejects the command
 * @throws ShellCommandUnresponsiveException if the device did not output any test result for
 * a period longer than the max time to output.
 * @throws IOException if connection to device was lost.
 *
 * @see #setMaxtimeToOutputResponse(int)
 */
void run(ITestRunListener... listeners)
        throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
        IOException;