private void pokeGpsExploit(final HardwareCallback callback, final int index) {
    Timeout.clearTimeout(gpsEventTimeout);

    // exploit a bug in the power manager widget
    final Intent poke = new Intent();
    poke.setClassName(
        "com.android.settings",
        "com.android.settings.widget.SettingsAppWidgetProvider"); //$NON-NLS-1$//$NON-NLS-2$
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3")); // $NON-NLS-1$
    mContext.sendBroadcast(poke);

    // sit & wait for event, otherwise trigger backup safety time-out
    gpsEventTimeout =
        Timeout.setTimeout(
            new Runnable() {
              public void run() {
                gpsEventTimeout = -1;
                unbindGps();
                callback.hardwareFailedToEnable(
                    index, HardwareCallback.REASON_GPS_TOGGLE_EXPLOIT_ATTEMPT);
              }
            },
            5000);
  }
Exemplo n.º 2
0
 public Page.Obj findElement(double timeoutS, By by) {
   timeout.override(timeoutS);
   try {
     return findElement(by);
   } catch (Exception xn) {
     throw Selen.Xn.unchecked(xn);
   } finally {
     timeout.reset();
   }
 }
Exemplo n.º 3
0
  @Test
  public void simpleTimeoutConstructorTest() {
    final AsyncCallback cb =
        new AsyncCallback() {
          @Override
          public void onCallback() {}
        };

    Timeout t = new Timeout(1492, cb);

    assertEquals(1492, t.getTimeout());
    assertEquals(cb, t.getCallback());
  }
Exemplo n.º 4
0
  public View[] getViews(String id, boolean scroll, View parent) {
    Context targetContext = instrumentation.getTargetContext();
    String packageName = targetContext.getPackageName();
    int viewId = targetContext.getResources().getIdentifier(id, "id", packageName);
    // Log.i("AAAAAA","id:"+viewId);

    Set<View> uniqueViewsMatchingId = new LinkedHashSet<View>();
    long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();

    while (SystemClock.uptimeMillis() <= endTime) {
      sleeper.sleep();
      List<View> list = null;
      if (parent == null) list = viewFetcher.getAllViews(true);
      else list = viewFetcher.getViews(parent, true);

      // LogEx.i("list in getViews: "+Arrays.deepToString(list.toArray()));

      for (View view : list) {
        Integer idOfView = Integer.valueOf(view.getId());
        if (idOfView.equals(viewId)
            && view.isShown()
            && view.getWidth() != 0
            && view.getHeight() != 0) {
          uniqueViewsMatchingId.add(view);
        }
      }
      if (scroll && scroller.scrollDown()) continue;
      break;
    }

    return uniqueViewsMatchingId.toArray(new View[0]);
  }
Exemplo n.º 5
0
  /**
   * Waits for and returns a View.
   *
   * @param index the index of the view
   * @param classToFilterby the class to filter
   * @return the specified View
   */
  public <T extends View> T waitForAndGetView(int index, Class<T> classToFilterBy) {
    long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
    while (SystemClock.uptimeMillis() <= endTime
        && !waitForView(classToFilterBy, index, true, true)) ;
    int numberOfUniqueViews = searcher.getNumberOfUniqueViews();
    ArrayList<T> views =
        RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(classToFilterBy));

    if (views.size() < numberOfUniqueViews) {
      int newIndex = index - (numberOfUniqueViews - views.size());
      if (newIndex >= 0) index = newIndex;
    }

    T view = null;
    try {
      view = views.get(index);
    } catch (IndexOutOfBoundsException exception) {
      int match = index + 1;
      if (match > 1) {
        Assert.fail(match + " " + classToFilterBy.getSimpleName() + "s" + " are not found!");
      } else {
        Assert.fail(classToFilterBy.getSimpleName() + " is not found!");
      }
    }
    views = null;
    return view;
  }
Exemplo n.º 6
0
  /**
   * Waits for a given view. Default timeout is 20 seconds.
   *
   * @param view the view to wait for
   * @return {@code true} if view is shown and {@code false} if it is not shown before the timeout
   */
  public boolean waitForView(View view) {
    View viewToWaitFor = waitForView(view, Timeout.getLargeTimeout(), true, true);
    if (viewToWaitFor != null) {
      return true;
    }

    return false;
  }
Exemplo n.º 7
0
  @Test
  public void timeoutCancelledTest() {
    final long now = System.currentTimeMillis();
    final AsyncCallback cb =
        new AsyncCallback() {
          @Override
          public void onCallback() {
            /*nop*/
          }
        };
    Timeout t1 = new Timeout(now + 2000, cb);
    assertTrue(t1.getCallback() == cb);

    t1.cancel();

    assertTrue(t1.getCallback() != cb);
    assertTrue(t1.isCancelled());
  }
Exemplo n.º 8
0
 @Override
 public T claim(Timeout timeout) throws PoolException, InterruptedException {
   if (timeout == null) {
     throw new IllegalArgumentException("Timeout cannot be null");
   }
   QSlot<T> slot;
   long deadline = timeout.getDeadline();
   do {
     long timeoutLeft = timeout.getTimeLeft(deadline);
     slot = live.poll(timeoutLeft, timeout.getBaseUnit());
     if (slot == null) {
       // we timed out while taking from the queue - just return null
       return null;
     }
     checkForPoison(slot);
   } while (isInvalid(slot));
   return slot.obj;
 }
 private long executeTimeouts() {
   // makes a defensive copy to avoid (1) CME (new timeouts are added this iteration) and (2) IO
   // starvation.
   TreeSet<Timeout> defensive = new TreeSet<Timeout>(timeouts); /*Sets.newTreeSet(timeouts);*/
   Iterator<Timeout> iter = defensive.iterator();
   final long now = System.currentTimeMillis();
   while (iter.hasNext()) {
     Timeout candidate = iter.next();
     if (candidate.getTimeout() > now) {
       break;
     }
     candidate.getCallback().onCallback();
     iter.remove();
     timeouts.remove(candidate);
     logger.debug("Timeout triggered: {}", candidate);
   }
   return timeouts.isEmpty()
       ? Long.MAX_VALUE
       : Math.max(1, timeouts.iterator().next().getTimeout() - now);
 }
Exemplo n.º 10
0
  /**
   * Returns a {@code View} that shows a given text, from the list of current {@code View}s of the
   * specified type.
   *
   * @param classToFilterBy which {@code View}s to choose from
   * @param text the text that the view shows
   * @param onlyVisible {@code true} if only visible texts on the screen should be returned
   * @return a {@code View} showing a given text, from the list of current {@code View}s of the
   *     specified type
   */
  public <T extends TextView> T getView(
      Class<T> classToFilterBy, String text, boolean onlyVisible) {

    T viewToReturn =
        (T)
            waiter.waitForText(
                classToFilterBy, text, 0, Timeout.getSmallTimeout(), false, onlyVisible, false);

    if (viewToReturn == null)
      Assert.fail(classToFilterBy.getSimpleName() + " with text: '" + text + "' is not found!");

    return viewToReturn;
  }
Exemplo n.º 11
0
  /** Convenient subsets of the {@link Timeout} enumeration for specifying scenario outcomes. */
  private enum TimeoutsToUse {
    ANY(Timeout.values()),
    PAST(Timeout.MIN, Timeout.MINUS_SMALL, Timeout.ZERO),
    FUTURE(Timeout.SMALL, Timeout.MAX),
    SMALL(Timeout.SMALL),
    FINITE(Timeout.MIN, Timeout.MINUS_SMALL, Timeout.ZERO, Timeout.SMALL),
    INFINITE(Timeout.LARGE, Timeout.MAX);

    final ImmutableList<Timeout> timeouts;

    private TimeoutsToUse(Timeout... timeouts) {
      this.timeouts = ImmutableList.copyOf(timeouts);
    }
  }
Exemplo n.º 12
0
  public void testRun() {
    /** Given: I am logged into a valid user profile starting from the main restaurant list */
    // Wait for activity: 'com.woww.woww.BaseDrawer'
    solo.waitForActivity(com.woww.woww.BaseDrawer.class, 2000);
    // Set default small timeout to 23836 milliseconds
    Timeout.setSmallTimeout(23836);
    // Click on ImageView
    solo.clickOnView(solo.getView(android.widget.ImageButton.class, 0));
    // Click on Log In
    solo.clickOnText(java.util.regex.Pattern.quote("Log In"));
    // Wait for activity: 'com.woww.woww.LoginActivity'
    assertTrue(
        "com.woww.woww.LoginActivity is not found!",
        solo.waitForActivity(com.woww.woww.LoginActivity.class));
    // Enter the text: 'changed'
    solo.clearEditText((android.widget.EditText) solo.getView(com.woww.woww.R.id.userName));
    solo.enterText((android.widget.EditText) solo.getView(com.woww.woww.R.id.userName), "changed");
    // Enter the text: 'c'
    solo.clearEditText((android.widget.EditText) solo.getView(com.woww.woww.R.id.password));
    solo.enterText((android.widget.EditText) solo.getView(com.woww.woww.R.id.password), "c");
    // Click on Login
    solo.clickOnView(solo.getView(com.woww.woww.R.id.loginButton));
    // Click on ImageView
    solo.clickOnView(solo.getView(android.widget.ImageButton.class, 0));

    /** When: I go to the profile page */
    // Click on Profile
    solo.clickOnText(java.util.regex.Pattern.quote("Profile"));
    ParseUser user = ParseUser.getCurrentUser();
    TextView profile = (TextView) solo.getView(R.id.profileName);

    /** Then: It is my profile page */
    assertEquals(
        "check that on same user profile as login name", user.getUsername(), profile.getText());

    /** When: When I go to my reviews from the profile page */
    // Long click Restaurant:   Rubio's Rating:   Review:   itwas
    solo.clickLongInList(1, 1);
    // Wait for activity: 'com.woww.woww.ViewUserReviewsActivity'

    /** Then: I am brought to my reviews */
    assertTrue(
        "com.woww.woww.ViewUserReviewsActivity is not found!",
        solo.waitForActivity(com.woww.woww.ViewUserReviewsActivity.class));
    // Press menu back key
    solo.goBack();
    // Press menu back key
    solo.goBack();
  }
Exemplo n.º 13
0
  public void testRun() throws InterruptedException {
    /*
     GIVEN THAT I AM ON THE MAIN RESTAURANT LIST
    */
    // Wait for activity: 'com.woww.woww.BaseDrawer'
    solo.waitForActivity(com.woww.woww.BaseDrawer.class, 2000);
    // Set default small timeout to 20009 milliseconds
    Timeout.setSmallTimeout(30009);
    // Scroll to ImageView
    android.widget.ListView listView0 =
        (android.widget.ListView) solo.getView(android.widget.ListView.class, 0);

    ArrayList<Restaurant> res;
    solo.scrollListToLine(listView0, 0);
    /*
     WHEN I OPEN THE MENU AND CLICK SORT BY PRICE
    */
    solo.clickOnView(solo.getView(android.widget.ImageView.class, 1));
    solo.clickInList(2, 0);
    Thread.sleep(2000);
    res = getListViewArray((RestaurantListAdapter) listView0.getAdapter());
    /*
    THEN THE LIST SHOULD BE SORTED BY PRICE IN ASCENDING ORDER
    */
    assertTrue(isOrderingValid(res, "price"));
    /*
     WHEN I OPEN THE MENU AND CLICK SORT BY RATING
    */
    solo.clickOnView(solo.getView(android.widget.ImageView.class, 1));
    solo.clickInList(3, 0);
    Thread.sleep(2000);
    res = getListViewArray((RestaurantListAdapter) listView0.getAdapter());
    /*
    THEN THE LIST SHOULD BE SORTED BY RATING IN DESCENDING ORDER
    */
    assertTrue(isOrderingValid(res, "rating"));
    /*
     WHEN I OPEN THE MENU AND CLICK SORT BY NAME
    */
    solo.clickOnView(solo.getView(android.widget.ImageView.class, 1));
    solo.clickInList(1, 0);
    Thread.sleep(5000);
    res = getListViewArray((RestaurantListAdapter) listView0.getAdapter());
    /*
     THEN THE LIST SHOULD BE SORTED BY NAME IN ALPHABETICAL ORDER
    */
    assertTrue(isOrderingValid(res, "name"));
  }
Exemplo n.º 14
0
  @Override
  protected void execute() {

    TransLayer trans = component.getHost().getTransLayer();

    if (listener != null) trans.removeTransMsgListener(listener, component.getPort());

    seqNr = getNewSequenceNumber();

    SeqMessage request = createReqMessage();
    request.setSeqNumber(seqNr);

    trans.send(request, to.getTransInfo(), to.getTransInfo().getPort(), TransProtocol.UDP);
    trans.addTransMsgListener(listener = this.new Listener(), component.getPort());

    timeout = this.new Timeout();
    timeout.scheduleWithDelay(getTimeout());
  }
Exemplo n.º 15
0
 @Override
 public int compareTo(DecoratedTimeout that) {
   long diff = timeout.getTimeout() - that.timeout.getTimeout();
   if (diff < 0) {
     return -1;
   } else if (diff > 0) {
     return 1;
   }
   if (channel != null && that.channel != null) {
     return channel.hashCode() - that.channel.hashCode();
   } else if (channel == null && that.channel != null) {
     return -1;
   } else if (channel != null && that.channel == null) {
     return -1;
   } else {
     return 0;
   }
 }
Exemplo n.º 16
0
  /** Gets the proper view to use for a screenshot. */
  private View getScreenshotView() {
    View decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindowDecorViews());
    final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();

    while (decorView == null) {

      final boolean timedOut = SystemClock.uptimeMillis() > endTime;

      if (timedOut) {
        return null;
      }
      sleeper.sleepMini();
      decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindowDecorViews());
    }
    wrapAllGLViews(decorView);

    return decorView;
  }
Exemplo n.º 17
0
  public View[] getViews(
      Method method, String value, View parent, boolean scroll, long timeout, View scroller) {
    if (timeout <= 0) timeout = Timeout.getSmallTimeout();
    long endTime = SystemClock.uptimeMillis() + timeout;

    Set<View> uniqueViewsMatchingId = new LinkedHashSet<View>();
    Pattern targetTextPattern = null;
    int targetId = 0;
    if (Method.REGEX_TEXT == method) targetTextPattern = Pattern.compile(value);
    else if (Method.ID == method) {
      Context targetContext = instrumentation.getTargetContext();
      String packageName = targetContext.getPackageName();
      targetId = targetContext.getResources().getIdentifier(value, "id", packageName);
    }
    while (SystemClock.uptimeMillis() <= endTime) {
      sleeper.sleep();
      List<View> list = null;
      if (parent == null) list = viewFetcher.getAllViews(true);
      else list = viewFetcher.getViews(parent, true);

      for (View view : list) {
        if (!view.isShown() || view.getWidth() == 0 || view.getHeight() == 0) continue;

        if (method == Method.REGEX_TEXT
            && (view instanceof TextView)
            && targetTextPattern.matcher(((TextView) view).getText()).find())
          uniqueViewsMatchingId.add(view);
        else if (method == Method.PLAIN_TEXT
            && (view instanceof TextView)
            && ((TextView) view).getText().toString().contains(value))
          uniqueViewsMatchingId.add(view);
        else if (method == Method.CLASS && view.getClass().getSimpleName().matches(value))
          uniqueViewsMatchingId.add(view);
        else if (method == Method.ID && view.getId() == targetId) uniqueViewsMatchingId.add(view);
      }

      if (scroll && scrollEx(Scroller.DOWN, false, scroller)) continue;

      break;
    }

    return uniqueViewsMatchingId.toArray(new View[0]);
  }
Exemplo n.º 18
0
  /**
   * Waits for two views to be shown.
   *
   * @param scrollMethod {@code true} if it's a method used for scrolling
   * @param classes the classes to wait for
   * @return {@code true} if any of the views are shown and {@code false} if none of the views are
   *     shown before the timeout
   */
  public <T extends View> boolean waitForViews(
      boolean scrollMethod, Class<? extends T>... classes) {
    final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();

    while (SystemClock.uptimeMillis() < endTime) {

      for (Class<? extends T> classToWaitFor : classes) {
        if (waitForView(classToWaitFor, 0, false, false)) {
          return true;
        }
      }
      if (scrollMethod) {
        scroller.scroll(Scroller.DOWN);
      } else {
        scroller.scrollDown();
      }
      sleeper.sleep();
    }
    return false;
  }
Exemplo n.º 19
0
  public void testRun() {
    // Wait for activity: 'course.labs.locationlab.PlaceViewActivity'
    solo.waitForActivity(course.labs.locationlab.PlaceViewActivity.class, 2000);

    // Set default small timeout to 55372 milliseconds
    Timeout.setSmallTimeout(55372);

    // Click on action bar item
    solo.clickOnActionBarItem(course.labs.locationlab.R.id.place_one);

    solo.sleep(2000);

    // Click on Get New Place
    solo.clickOnView(solo.getView(course.labs.locationlab.R.id.footer));

    solo.sleep(5000);

    // Click on action bar item
    solo.clickOnActionBarItem(course.labs.locationlab.R.id.print_badges);
  }
  @Before("timeoutExecution(timeout)")
  public void beforeTimeoutExecution(JoinPoint thisJoinPoint, Timeout timeout) {
    final IPluginExecutable executable = (IPluginExecutable) thisJoinPoint.getTarget();

    activeExecutions.add(executable);

    try {
      timer.schedule(
          new TimerTask() {
            @Override
            public void run() {
              if (activeExecutions.contains(executable)) {
                executable.interrupted();
              }
            }
          },
          timeout.value());
    } catch (SecurityException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 21
0
 @Override
 public void throwIfReached() throws IOException {
   delegate.throwIfReached();
 }
Exemplo n.º 22
0
 @Override
 public Timeout clearDeadline() {
   return delegate.clearDeadline();
 }
Exemplo n.º 23
0
 @Override
 public Timeout clearTimeout() {
   return delegate.clearTimeout();
 }
Exemplo n.º 24
0
 @Override
 public Timeout deadlineNanoTime(long deadlineNanoTime) {
   return delegate.deadlineNanoTime(deadlineNanoTime);
 }
Exemplo n.º 25
0
 @Override
 public long deadlineNanoTime() {
   return delegate.deadlineNanoTime();
 }
Exemplo n.º 26
-1
  private void testSampler(final int count, float frequency) {
    server.setMaxConnections(1);
    final ArrayList<String> expected = new ArrayList<String>(count);
    Timeout gen =
        new Timeout() {
          Tag tag = new SimpleTag(0);
          int sent = 0;

          @Override
          public void onSample(DatawireEvent e) {
            String body = template.render(sent);
            expected.add(body);
            Message message = Message.Factory.create();
            message.setBody(new AmqpValue(body));
            DatawireUtils.send(e.getLink(), tag, message);
            sent += 1;
            if (sent >= count) {
              e.getLink().close();
              cancel();
            }
          }
        };
    Sender snd =
        Sender.Builder()
            .withTarget(server.address())
            .withHandlers(new Sampler(gen, frequency))
            .create();
    reactor.getHandler().add(snd);
    gen.setTimeout(reactor, 2000);
    snd.start(reactor);
    reactor.run();
    assertTrue("Sampling timed out", gen.isCancelled());
    assertEquals("Expected messages", expected, sink.getMessages());
  }
Exemplo n.º 27
-1
  private static void removeTimeouts(Spannable buf) {
    Timeout[] timeout = buf.getSpans(0, buf.length(), Timeout.class);

    for (int i = 0; i < timeout.length; i++) {
      Timeout t = timeout[i];

      t.removeCallbacks(t);
      t.mBuffer = null;
      buf.removeSpan(t);
    }
  }
Exemplo n.º 28
-1
 @Override
 public int compare(Timeout lhs, Timeout rhs) {
   if (lhs == rhs) {
     return 0;
   }
   long diff = lhs.getTimeout() - rhs.getTimeout();
   if (diff <= 0) {
     return -1;
   }
   return 1; /// else if (diff > 0) {
 }
Exemplo n.º 29
-1
  /**
   * Creates a gateway instance for the given <code>gatewayInterface</code>. The returned instance
   * is a Proxy that implements that interface.
   *
   * @param gatewayInterface The interface declaring the gateway methods
   * @param <T> The interface declaring the gateway methods
   * @return A Proxy implementation implementing the given interface
   */
  @SuppressWarnings("unchecked")
  public <T> T createGateway(Class<T> gatewayInterface) {
    Map<Method, InvocationHandler> dispatchers = new HashMap<Method, InvocationHandler>();
    for (Method gatewayMethod : gatewayInterface.getMethods()) {
      MetaDataExtractor[] extractors = extractMetaData(gatewayMethod.getParameterAnnotations());

      InvocationHandler dispatcher =
          new DispatchOnInvocationHandler(
              commandBus, retryScheduler,
              dispatchInterceptors, extractors);
      final Class<?>[] arguments = gatewayMethod.getParameterTypes();
      if (Future.class.equals(gatewayMethod.getReturnType())) {
        // no wrapping
      } else if (arguments.length >= 3
          && TimeUnit.class.isAssignableFrom(arguments[arguments.length - 1])
          && (long.class.isAssignableFrom(arguments[arguments.length - 2])
              || int.class.isAssignableFrom(arguments[arguments.length - 2]))) {
        dispatcher =
            wrapToReturnWithTimeoutInArguments(
                dispatcher, arguments.length - 2, arguments.length - 1);
      } else {
        Timeout timeout = gatewayMethod.getAnnotation(Timeout.class);
        if (timeout == null) {
          timeout = gatewayMethod.getDeclaringClass().getAnnotation(Timeout.class);
        }
        if (timeout != null) {
          dispatcher = wrapToReturnWithFixedTimeout(dispatcher, timeout.value(), timeout.unit());
        } else if (!Void.TYPE.equals(gatewayMethod.getReturnType())
            || gatewayMethod.getExceptionTypes().length > 0) {
          dispatcher = wrapToWaitForResult(dispatcher);
        } else {
          dispatcher = wrapToFireAndForget(dispatcher);
        }
      }
      Class<?>[] declaredExceptions = gatewayMethod.getExceptionTypes();
      if (!contains(declaredExceptions, TimeoutException.class)) {
        dispatcher = wrapToReturnNullOnTimeout(dispatcher);
      }
      if (!contains(declaredExceptions, InterruptedException.class)) {
        dispatcher = wrapToReturnNullOnInterrupted(dispatcher);
      }
      dispatcher = wrapUndeclaredExceptions(dispatcher, declaredExceptions);
      dispatchers.put(gatewayMethod, dispatcher);
    }

    return gatewayInterface.cast(
        Proxy.newProxyInstance(
            gatewayInterface.getClassLoader(),
            new Class[] {gatewayInterface},
            new GatewayInvocationHandler(
                dispatchers, commandBus, retryScheduler, dispatchInterceptors)));
  }
Exemplo n.º 30
-1
  public View[] getViews(View parent, String text, boolean scroll) {
    text = ".*" + text + ".*";

    Set<View> uniqueViewsMatchingId = new LinkedHashSet<View>();
    long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();

    while (SystemClock.uptimeMillis() <= endTime) {
      sleeper.sleep();
      List<View> list = null;
      if (parent == null) list = viewFetcher.getAllViews(true);
      else list = viewFetcher.getViews(parent, true);

      for (View view : list) {
        if ((view instanceof TextView)
            && view.isShown()
            && ((TextView) view).getText().toString().matches(text)
            && view.getWidth() != 0
            && view.getHeight() != 0) {
          uniqueViewsMatchingId.add(view);
        }
      }
      if (scroll && scroller.scrollDown()) continue;

      break;
    }

    return uniqueViewsMatchingId.toArray(new View[0]);
  }