Search in sources :

Example 1 with SuppressForbidden

use of com.facebook.buck.annotations.SuppressForbidden in project buck by facebook.

the class AdbHelper method startActivity.

@SuppressForbidden
public int startActivity(SourcePathResolver pathResolver, HasInstallableApk hasInstallableApk, @Nullable String activity, boolean waitForDebugger) throws IOException, InterruptedException {
    // Might need the package name and activities from the AndroidManifest.
    Path pathToManifest = pathResolver.getAbsolutePath(hasInstallableApk.getApkInfo().getManifestPath());
    AndroidManifestReader reader = DefaultAndroidManifestReader.forPath(hasInstallableApk.getProjectFilesystem().resolve(pathToManifest));
    if (activity == null) {
        // Get list of activities that show up in the launcher.
        List<String> launcherActivities = reader.getLauncherActivities();
        // Sanity check.
        if (launcherActivities.isEmpty()) {
            console.printBuildFailure("No launchable activities found.");
            return 1;
        } else if (launcherActivities.size() > 1) {
            console.printBuildFailure("Default activity is ambiguous.");
            return 1;
        }
        // Construct a component for the '-n' argument of 'adb shell am start'.
        activity = reader.getPackage() + "/" + launcherActivities.get(0);
    } else if (!activity.contains("/")) {
        // If no package name was provided, assume the one in the manifest.
        activity = reader.getPackage() + "/" + activity;
    }
    final String activityToRun = activity;
    PrintStream stdOut = console.getStdOut();
    stdOut.println(String.format("Starting activity %s...", activityToRun));
    StartActivityEvent.Started started = StartActivityEvent.started(hasInstallableApk.getBuildTarget(), activityToRun);
    getBuckEventBus().post(started);
    boolean success = adbCall(new AdbHelper.AdbCallable() {

        @Override
        public boolean call(IDevice device) throws Exception {
            String err = deviceStartActivity(device, activityToRun, waitForDebugger);
            if (err != null) {
                console.printBuildFailure(err);
                return false;
            } else {
                return true;
            }
        }

        @Override
        public String toString() {
            return "start activity";
        }
    }, false);
    getBuckEventBus().post(StartActivityEvent.finished(started, success));
    return success ? 0 : 1;
}
Also used : Path(java.nio.file.Path) PrintStream(java.io.PrintStream) StartActivityEvent(com.facebook.buck.event.StartActivityEvent) IDevice(com.android.ddmlib.IDevice) AdbCommandRejectedException(com.android.ddmlib.AdbCommandRejectedException) InterruptionFailedException(com.facebook.buck.util.InterruptionFailedException) CancellationException(java.util.concurrent.CancellationException) InstallException(com.android.ddmlib.InstallException) TimeoutException(com.android.ddmlib.TimeoutException) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) ExecutionException(java.util.concurrent.ExecutionException) ShellCommandUnresponsiveException(com.android.ddmlib.ShellCommandUnresponsiveException) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 2 with SuppressForbidden

use of com.facebook.buck.annotations.SuppressForbidden in project buck by facebook.

the class AdbHelper method adbCall.

/**
   * Execute an {@link AdbCallable} for all matching devices. This functions performs device
   * filtering based on three possible arguments:
   *
   *  -e (emulator-only) - only emulators are passing the filter
   *  -d (device-only) - only real devices are passing the filter
   *  -s (serial) - only device/emulator with specific serial number are passing the filter
   *
   *  If more than one device matches the filter this function will fail unless multi-install
   *  mode is enabled (-x). This flag is used as a marker that user understands that multiple
   *  devices will be used to install the apk if needed.
   */
@SuppressWarnings("PMD.EmptyCatchBlock")
@SuppressForbidden
public boolean adbCall(AdbCallable adbCallable, boolean quiet) throws InterruptedException {
    List<IDevice> devices;
    try (SimplePerfEvent.Scope ignored = SimplePerfEvent.scope(buckEventBus, "set_up_adb_call")) {
        devices = getDevices(quiet);
        if (devices.size() == 0) {
            return false;
        }
    }
    int adbThreadCount = options.getAdbThreadCount();
    if (adbThreadCount <= 0) {
        adbThreadCount = devices.size();
    }
    // Start executions on all matching devices.
    List<ListenableFuture<Boolean>> futures = Lists.newArrayList();
    ListeningExecutorService executorService = listeningDecorator(newMultiThreadExecutor(new CommandThreadFactory(getClass().getSimpleName()), adbThreadCount));
    for (final IDevice device : devices) {
        futures.add(executorService.submit(adbCallable.forDevice(device)));
    }
    // Wait for all executions to complete or fail.
    List<Boolean> results = null;
    try {
        results = Futures.allAsList(futures).get();
    } catch (ExecutionException ex) {
        console.printBuildFailure("Failed: " + adbCallable);
        ex.printStackTrace(console.getStdErr());
        return false;
    } catch (InterruptedException e) {
        try {
            Futures.allAsList(futures).cancel(true);
        } catch (CancellationException ignored) {
        // Rethrow original InterruptedException instead.
        }
        Thread.currentThread().interrupt();
        throw e;
    } finally {
        MostExecutors.shutdownOrThrow(executorService, 10, TimeUnit.MINUTES, new InterruptionFailedException("Failed to shutdown ExecutorService."));
    }
    int successCount = 0;
    for (Boolean result : results) {
        if (result) {
            successCount++;
        }
    }
    int failureCount = results.size() - successCount;
    // Report results.
    if (successCount > 0 && !quiet) {
        console.printSuccess(String.format("Successfully ran %s on %d device(s)", adbCallable, successCount));
    }
    if (failureCount > 0) {
        console.printBuildFailure(String.format("Failed to %s on %d device(s).", adbCallable, failureCount));
    }
    return failureCount == 0;
}
Also used : CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) IDevice(com.android.ddmlib.IDevice) InterruptionFailedException(com.facebook.buck.util.InterruptionFailedException) CancellationException(java.util.concurrent.CancellationException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) SimplePerfEvent(com.facebook.buck.event.SimplePerfEvent) ExecutionException(java.util.concurrent.ExecutionException) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 3 with SuppressForbidden

use of com.facebook.buck.annotations.SuppressForbidden in project buck by facebook.

the class AdbHelper method installApk.

/**
   * Install apk on all matching devices. This functions performs device
   * filtering based on three possible arguments:
   *
   *  -e (emulator-only) - only emulators are passing the filter
   *  -d (device-only) - only real devices are passing the filter
   *  -s (serial) - only device/emulator with specific serial number are passing the filter
   *
   *  If more than one device matches the filter this function will fail unless multi-install
   *  mode is enabled (-x). This flag is used as a marker that user understands that multiple
   *  devices will be used to install the apk if needed.
   */
@SuppressForbidden
public boolean installApk(SourcePathResolver pathResolver, HasInstallableApk hasInstallableApk, boolean installViaSd, boolean quiet) throws InterruptedException {
    Optional<ExopackageInfo> exopackageInfo = hasInstallableApk.getApkInfo().getExopackageInfo();
    if (exopackageInfo.isPresent()) {
        return new ExopackageInstaller(pathResolver, context, this, hasInstallableApk).install(quiet);
    }
    InstallEvent.Started started = InstallEvent.started(hasInstallableApk.getBuildTarget());
    if (!quiet) {
        getBuckEventBus().post(started);
    }
    File apk = pathResolver.getAbsolutePath(hasInstallableApk.getApkInfo().getApkPath()).toFile();
    boolean success = adbCall(new AdbHelper.AdbCallable() {

        @Override
        public boolean call(IDevice device) throws Exception {
            return installApkOnDevice(device, apk, installViaSd, quiet);
        }

        @Override
        @SuppressForbidden
        public String toString() {
            return String.format("install apk %s", hasInstallableApk.getBuildTarget().toString());
        }
    }, quiet);
    if (!quiet) {
        AdbHelper.tryToExtractPackageNameFromManifest(pathResolver, hasInstallableApk.getApkInfo());
        getBuckEventBus().post(InstallEvent.finished(started, success, Optional.empty(), Optional.of(AdbHelper.tryToExtractPackageNameFromManifest(pathResolver, hasInstallableApk.getApkInfo()))));
    }
    return success;
}
Also used : IDevice(com.android.ddmlib.IDevice) AdbCommandRejectedException(com.android.ddmlib.AdbCommandRejectedException) InterruptionFailedException(com.facebook.buck.util.InterruptionFailedException) CancellationException(java.util.concurrent.CancellationException) InstallException(com.android.ddmlib.InstallException) TimeoutException(com.android.ddmlib.TimeoutException) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) ExecutionException(java.util.concurrent.ExecutionException) ShellCommandUnresponsiveException(com.android.ddmlib.ShellCommandUnresponsiveException) InstallEvent(com.facebook.buck.event.InstallEvent) ExopackageInfo(com.facebook.buck.rules.ExopackageInfo) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden) File(java.io.File) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 4 with SuppressForbidden

use of com.facebook.buck.annotations.SuppressForbidden in project buck by facebook.

the class AdbHelper method getDevices.

@SuppressForbidden
public List<IDevice> getDevices(boolean quiet) throws InterruptedException {
    // Initialize adb connection.
    AndroidDebugBridge adb = createAdb(context);
    if (adb == null) {
        console.printBuildFailure("Failed to create adb connection.");
        return Lists.newArrayList();
    }
    // Build list of matching devices.
    List<IDevice> devices = filterDevices(adb.getDevices());
    if (devices != null && devices.size() > 1) {
        // Found multiple devices but multi-install mode is not enabled.
        if (!options.isMultiInstallModeEnabled()) {
            console.printBuildFailure(String.format("%d device(s) matches specified device filter (1 expected).\n" + "Either disconnect other devices or enable multi-install mode (%s).", devices.size(), AdbOptions.MULTI_INSTALL_MODE_SHORT_ARG));
            return Lists.newArrayList();
        }
        if (!quiet) {
            // Report if multiple devices are matching the filter.
            console.getStdOut().printf("Found " + devices.size() + " matching devices.\n");
        }
    }
    if (devices == null && restartAdbOnFailure) {
        console.printErrorText("No devices found with adb, restarting adb-server.");
        adb.restart();
        devices = filterDevices(adb.getDevices());
    }
    if (devices == null) {
        return Lists.newArrayList();
    }
    return devices;
}
Also used : IDevice(com.android.ddmlib.IDevice) AndroidDebugBridge(com.android.ddmlib.AndroidDebugBridge) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 5 with SuppressForbidden

use of com.facebook.buck.annotations.SuppressForbidden in project buck by facebook.

the class AdbHelper method uninstallApkFromDevice.

/**
   * Uninstalls apk from specific device. Reports success or failure to console.
   * It's currently here because it's used both by {@link com.facebook.buck.cli.InstallCommand} and
   * {@link com.facebook.buck.cli.UninstallCommand}.
   */
@SuppressWarnings("PMD.PrematureDeclaration")
@SuppressForbidden
private boolean uninstallApkFromDevice(IDevice device, String packageName, boolean keepData) {
    String name;
    if (device.isEmulator()) {
        name = device.getSerialNumber() + " (" + device.getAvdName() + ")";
    } else {
        name = device.getSerialNumber();
        String model = device.getProperty("ro.product.model");
        if (model != null) {
            name += " (" + model + ")";
        }
    }
    PrintStream stdOut = console.getStdOut();
    stdOut.printf("Removing apk from %s.\n", name);
    try {
        long start = System.currentTimeMillis();
        String reason = deviceUninstallPackage(device, packageName, keepData);
        long end = System.currentTimeMillis();
        if (reason != null) {
            console.printBuildFailure(String.format("Failed to uninstall apk from %s: %s.", name, reason));
            return false;
        }
        long delta = end - start;
        stdOut.printf("Uninstalled apk from %s in %d.%03ds.\n", name, delta / 1000, delta % 1000);
        return true;
    } catch (InstallException ex) {
        console.printBuildFailure(String.format("Failed to uninstall apk from %s.", name));
        ex.printStackTrace(console.getStdErr());
        return false;
    }
}
Also used : PrintStream(java.io.PrintStream) InstallException(com.android.ddmlib.InstallException) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Aggregations

SuppressForbidden (com.facebook.buck.annotations.SuppressForbidden)7 IDevice (com.android.ddmlib.IDevice)5 AdbCommandRejectedException (com.android.ddmlib.AdbCommandRejectedException)3 InstallException (com.android.ddmlib.InstallException)3 ShellCommandUnresponsiveException (com.android.ddmlib.ShellCommandUnresponsiveException)3 TimeoutException (com.android.ddmlib.TimeoutException)3 InterruptionFailedException (com.facebook.buck.util.InterruptionFailedException)3 IOException (java.io.IOException)3 CancellationException (java.util.concurrent.CancellationException)3 ExecutionException (java.util.concurrent.ExecutionException)3 HumanReadableException (com.facebook.buck.util.HumanReadableException)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 PrintStream (java.io.PrintStream)2 AndroidDebugBridge (com.android.ddmlib.AndroidDebugBridge)1 CollectingOutputReceiver (com.android.ddmlib.CollectingOutputReceiver)1 InstallEvent (com.facebook.buck.event.InstallEvent)1 SimplePerfEvent (com.facebook.buck.event.SimplePerfEvent)1 StartActivityEvent (com.facebook.buck.event.StartActivityEvent)1 CommandThreadFactory (com.facebook.buck.log.CommandThreadFactory)1 ExopackageInfo (com.facebook.buck.rules.ExopackageInfo)1