Пример #1
0
  /**
   * Test behavior when a cache object goes into the "disabled" state while it's in the valid state.
   * The cache remains in the valid state but it loses its data and obtains an error status.
   */
  public void testDisableWhileValid() throws InterruptedException, ExecutionException {
    // Request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Complete the request
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    Assert.assertEquals(Integer.valueOf(1), q.get());

    // Disable the cache
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fTestCache.set(null, ERROR_TARGET_RUNNING, true);
          }
        });

    // Check final state
    assertCacheValidWithoutData();
  }
Пример #2
0
  public void testResetWhileValid() throws InterruptedException, ExecutionException {
    // Request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    q.get();

    // Disable cache
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fTestCache.reset();
          }
        });

    // Check final state
    assertCacheResetWithoutData();
  }
Пример #3
0
  /**
   * Test behavior when a cache object goes into the "disabled" state while an update request is
   * ongoing. The subsequent completion of the request should have no effect on the cache
   */
  public void testDisableWhilePending() throws InterruptedException, ExecutionException {
    // Request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    // Disable the cache
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fTestCache.set(null, ERROR_TARGET_RUNNING, true);
          }
        });

    assertCacheValidWithoutData();

    // Complete the retrieve RM. Note that the disabling of the cache above
    // disassociates it from its retrieval RM. Thus regardless of how that
    // request completes, it does not affect the cache.
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    // Validate that cache is still disabled without data.
    assertCacheValidWithoutData();
  }
Пример #4
0
  private IPeerNode getPeerNode(final String peerId) {
    if (peerId != null) {
      final AtomicReference<IPeerNode> peerNode = new AtomicReference<IPeerNode>();

      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              IPeerModel model = ModelManager.getPeerModel();
              Assert.isNotNull(model);
              peerNode.set(
                  model.getService(IPeerModelLookupService.class).lkupPeerModelById(peerId));
            }
          };

      if (Protocol.isDispatchThread()) {
        runnable.run();
      } else {
        Protocol.invokeAndWait(runnable);
      }

      return peerNode.get();
    }

    return null;
  }
Пример #5
0
  public void testCancelWhilePendingWithTwoClients()
      throws InterruptedException, ExecutionException {

    // Request data from cache. Use an additional invokeAndWait to
    // ensure both update requests are initiated before we wait
    // for retrieval to start
    Query<Integer> q1 = new TestQuery();
    q1.invoke();
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {}
        });

    // Request data from cache again
    Query<Integer> q2 = new TestQuery();
    q2.invoke();
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {}
        });

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Cancel the first client request
    q1.cancel(true);
    try {
      q1.get();
      Assert.fail("Expected a cancellation exception");
    } catch (CancellationException e) {
    } // Expected exception;
    assertCacheWaiting();

    // Cancel the second request
    q2.cancel(true);
    try {
      q2.get();
      Assert.fail("Expected a cancellation exception");
    } catch (CancellationException e) {
    } // Expected exception;

    assertCacheInvalidAndWithCanceledRM();

    // Completed the retrieve RM
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    // Validate that cache didn't accept the result after its RM was canceled
    assertCacheInvalidAndWithCanceledRM();
  }
Пример #6
0
  public void testCancelWhilePending2() throws InterruptedException, ExecutionException {
    // Request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Cancel the client request
    q.cancel(true);
    try {
      q.get();
      Assert.fail("Expected a cancellation exception");
    } catch (CancellationException e) {
    } // Expected exception;

    assertCacheInvalidAndWithCanceledRM();

    // Simulate retrieval logic that is regularly checking the RM's cancel
    // status and has discovered that the request has been canceled. It
    // technically does not need to explicitly set a cancel status object in
    // the RM, thanks to RequestMonitor.getStatus() automatically returning
    // Status.CANCEL_STATUS when its in the cancel state. So here we
    // simulate the retrieval logic just aborting its operations and
    // completing the RM. Note that it hasn't provided the data to the
    // cache.
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.done();
          }
        });

    assertCacheInvalidAndWithCanceledRM();
  }
Пример #7
0
  public void testCancelWhilePending() throws InterruptedException, ExecutionException {
    // Request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Cancel the client request
    q.cancel(true);
    try {
      q.get();
      Assert.fail("Expected a cancellation exception");
    } catch (CancellationException e) {
    } // Expected exception;

    assertCacheInvalidAndWithCanceledRM();

    // Simulate the retrieval completing successfully despite the cancel
    // request. Perhaps the retrieval logic isn't checking the RM status.
    // Even if it is checking, it may have gotten passed its last checkpoint
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    // Validate that cache didn't accept the result after its RM was canceled
    assertCacheInvalidAndWithCanceledRM();
  }
Пример #8
0
  public void testGetWithManyClients() throws InterruptedException, ExecutionException {
    // Check initial state
    Assert.assertFalse(fTestCache.isValid());

    // Request data from cache
    List<Query<Integer>> qList = new ArrayList<Query<Integer>>();
    for (int i = 0; i < 10; i++) {
      Query<Integer> q = new TestQuery();
      q.invoke();
      qList.add(q);
    }
    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Check state while waiting for data
    Assert.assertFalse(fTestCache.isValid());

    // Set the data to the callback
    Protocol.invokeLater(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    for (Query<Integer> q : qList) {
      Assert.assertEquals(1, (int) q.get());
    }

    // Check final state
    assertCacheValidWithData(1);
  }
Пример #9
0
  public void testCancelWhilePending3() throws InterruptedException, ExecutionException {
    // Request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Cancel the client request
    q.cancel(true);
    try {
      q.get();
      Assert.fail("Expected a cancellation exception");
    } catch (CancellationException e) {
    } // Expected exception;

    assertCacheInvalidAndWithCanceledRM();

    // Simulate retrieval logic that is regularly checking the RM's cancel
    // status and has discovered that the request has been canceled. It
    // aborts its processing, sets STATUS.CANCEL_STATUS in the RM and
    // completes it.
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setError(new CancellationException());
            fRetrieveRm.done();
          }
        });

    // Validate that cache didn't accept the result after its RM was canceled
    assertCacheInvalidAndWithCanceledRM();
  }
Пример #10
0
  public void testGet() throws InterruptedException, ExecutionException {
    // Request data from cache
    Query<Integer> q = new TestQuery();

    // Check initial state
    Assert.assertFalse(fTestCache.isValid());

    q.invoke();

    // Wait until the cache requests the data.
    waitForRetrieveRm();

    // Check state while waiting for data
    Assert.assertFalse(fTestCache.isValid());

    // Complete the cache's retrieve data request.
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();

            // Check that the data is available in the cache immediately
            // (in the same dispatch cycle).
            Assert.assertEquals(1, (int) fTestCache.getData());
            Assert.assertTrue(fTestCache.isValid());
          }
        });

    Assert.assertEquals(1, (int) q.get());

    // Re-check final state
    assertCacheValidWithData(1);
  }
Пример #11
0
  public void testGetWithTwoClients() throws InterruptedException, ExecutionException {
    // Check initial state
    Assert.assertFalse(fTestCache.isValid());

    // Request data from cache
    Query<Integer> q1 = new TestQuery();
    q1.invoke();

    // Request data from cache again
    Query<Integer> q2 = new TestQuery();
    q2.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Check state while waiting for data
    Assert.assertFalse(fTestCache.isValid());

    // Set the data to the callback
    Protocol.invokeLater(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    Assert.assertEquals(1, (int) q1.get());
    Assert.assertEquals(1, (int) q2.get());

    // Check final state
    assertCacheValidWithData(1);
  }
Пример #12
0
  /* (non-Javadoc)
   * @see org.eclipse.tcf.te.runtime.stepper.interfaces.IStep#execute(org.eclipse.tcf.te.runtime.stepper.interfaces.IStepContext, org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer, org.eclipse.tcf.te.runtime.stepper.interfaces.IFullQualifiedId, org.eclipse.core.runtime.IProgressMonitor, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback)
   */
  @Override
  public void execute(
      IStepContext context,
      IPropertiesContainer data,
      IFullQualifiedId fullQualifiedId,
      IProgressMonitor monitor,
      final ICallback callback) {
    IPeerNode peerNode = getActivePeerModelContext(context, data, fullQualifiedId);
    if (peerNode != null) {
      IRuntimeModel model = ModelManager.getRuntimeModel(peerNode);
      final IModelChannelService service =
          model != null ? model.getService(IModelChannelService.class) : null;
      if (service != null) {
        Runnable runnable =
            new Runnable() {
              @Override
              public void run() {
                service.openChannel(
                    new IModelChannelService.DoneOpenChannel() {
                      @Override
                      public void doneOpenChannel(Throwable error, IChannel channel) {
                        callback.done(InitializeModelStep.this, StatusHelper.getStatus(error));
                      }
                    });
              }
            };

        Protocol.invokeLater(runnable);
      } else {
        callback.done(InitializeModelStep.this, Status.OK_STATUS);
      }
    } else {
      callback.done(InitializeModelStep.this, Status.OK_STATUS);
    }
  }
Пример #13
0
  /* (non-Javadoc)
   * @see org.eclipse.core.runtime.PlatformObject#getAdapter(java.lang.Class)
   */
  @Override
  public Object getAdapter(final Class adapter) {
    // NOTE: The getAdapter(...) method can be invoked from many place and
    //       many threads where we cannot control the calls. Therefore, this
    //       method is allowed be called from any thread.
    final AtomicReference<Object> object = new AtomicReference<Object>();
    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            object.set(doGetAdapter(adapter));
          }
        };

    if (Protocol.isDispatchThread()) runnable.run();
    else Protocol.invokeAndWait(runnable);

    return object.get() != null ? object.get() : super.getAdapter(adapter);
  }
Пример #14
0
  /* (non-Javadoc)
   * @see org.eclipse.tcf.te.runtime.properties.PropertiesContainer#toString()
   */
  @Override
  public String toString() {
    final StringBuilder buffer = new StringBuilder(getClass().getSimpleName());

    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            IPeer peer = getPeer();
            buffer.append(": id=" + peer.getID()); // $NON-NLS-1$
            buffer.append(", name=" + peer.getName()); // $NON-NLS-1$
          }
        };

    if (Protocol.isDispatchThread()) runnable.run();
    else Protocol.invokeAndWait(runnable);

    buffer.append(", " + super.toString()); // $NON-NLS-1$
    return buffer.toString();
  }
Пример #15
0
  public void testSetWithValue() throws InterruptedException, ExecutionException {
    // Disable the cache
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fTestCache.set(2, null, true);
          }
        });

    // Validate that cache is disabled without data.
    assertCacheValidWithData(2);
  }
Пример #16
0
  /* (non-Javadoc)
   * @see org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModel#getRemotePeerId()
   */
  @Override
  public String getRemotePeerId() {
    // If the peer is a remote peer by itself, than we return getPeerId()
    if ("RemotePeer".equals(getPeer().getClass().getSimpleName())) { // $NON-NLS-1$
      return getPeerId();
    }

    // Try to determine the remote peer ID
    final AtomicReference<String> remotePeerId = new AtomicReference<String>();
    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            remotePeerId.set(getPeer().getAttributes().get("remote.id.transient")); // $NON-NLS-1$
          }
        };

    if (Protocol.isDispatchThread()) runnable.run();
    else Protocol.invokeAndWait(runnable);

    return remotePeerId.get();
  }
Пример #17
0
 /**
  * Return breakpoint status info for all active TCF debug sessions.
  *
  * @param breakpoint
  * @return breakpoint status as defined by TCF Breakpoints service.
  */
 Map<TCFLaunch, Map<String, Object>> getBreakpointStatus(IBreakpoint breakpoint) {
   assert Protocol.isDispatchThread();
   Map<TCFLaunch, Map<String, Object>> map = new HashMap<TCFLaunch, Map<String, Object>>();
   if (disposed) return null;
   ILaunch[] launches = DebugPlugin.getDefault().getLaunchManager().getLaunches();
   for (ILaunch l : launches) {
     if (l instanceof TCFLaunch) {
       TCFLaunch launch = (TCFLaunch) l;
       TCFBreakpointsStatus bs = launch.getBreakpointsStatus();
       if (bs != null) map.put(launch, bs.getStatus(breakpoint));
     }
   }
   return map;
 }
Пример #18
0
 @Override
 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
   updateAnnotations(part.getSite().getWorkbenchWindow(), (TCFLaunch) null);
   if (selection instanceof IStructuredSelection) {
     final Object obj = ((IStructuredSelection) selection).getFirstElement();
     if (obj instanceof TCFNodeStackFrame && ((TCFNodeStackFrame) obj).isTraceLimit()) {
       Protocol.invokeLater(
           new Runnable() {
             public void run() {
               ((TCFNodeStackFrame) obj).riseTraceLimit();
             }
           });
     }
   }
 }
Пример #19
0
  /**
   * Test behavior when a cache object is asked to update itself after it has become "disabled".
   * Since a "disabled" cache is in the valid state, a request for it to update from the source
   * should be ignored. However, the client callback is not completed until next state change in
   * cache.
   */
  public void testDisableBeforeRequest() throws InterruptedException, ExecutionException {
    // Disable the cache
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fTestCache.set(null, ERROR_TARGET_RUNNING, true);
          }
        });

    assertCacheValidWithoutData();

    // Try to request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    Thread.sleep(100);

    // Retrieval should never have been made.
    Assert.assertEquals(null, fRetrieveRm);

    // Disable the cache.  This should trigger the qery to complete.
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fTestCache.set(null, new Throwable("Cache invalid"), false);
          }
        });

    // The cache has no data so the query should have failed
    try {
      q.get();
      Assert.fail("expected an exeption");
    } catch (ExecutionException e) {
      // expected the exception
    }
  }
Пример #20
0
 public void dispose() {
   if (disposed) return;
   assert Protocol.isDispatchThread();
   disposed = true;
   launch_manager.removeLaunchConfigurationListener(launch_conf_listener);
   TCFLaunch.removeListener(launch_listener);
   displayExec(
       new Runnable() {
         public void run() {
           if (!started) return;
           PlatformUI.getWorkbench().removeWindowListener(window_listener);
           for (IWorkbenchWindow window : windows.keySet()) {
             window
                 .getSelectionService()
                 .removeSelectionListener(IDebugUIConstants.ID_DEBUG_VIEW, selection_listener);
             windows.get(window).dispose();
           }
           windows.clear();
         }
       });
 }
Пример #21
0
 public TCFAnnotationManager() {
   assert Protocol.isDispatchThread();
   TCFLaunch.addListener(launch_listener);
   launch_manager.addLaunchConfigurationListener(launch_conf_listener);
   displayExec(
       new Runnable() {
         public void run() {
           if (!PlatformUI.isWorkbenchRunning() || PlatformUI.getWorkbench().isStarting()) {
             display.timerExec(200, this);
           } else if (!PlatformUI.getWorkbench().isClosing()) {
             started = true;
             PlatformUI.getWorkbench().addWindowListener(window_listener);
             for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
               window_listener.windowOpened(window);
             }
             IWorkbenchWindow w = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
             if (w != null) window_listener.windowActivated(w);
           }
         }
       });
 }
Пример #22
0
 /**
  * Return breakpoint status text for all active TCF debug sessions.
  *
  * @param breakpoint
  * @return breakpoint status as a string.
  */
 @SuppressWarnings("unchecked")
 String getBreakpointStatusText(IBreakpoint breakpoint) {
   assert Protocol.isDispatchThread();
   String error = null;
   for (Map<String, Object> map : getBreakpointStatus(breakpoint).values()) {
     if (map != null) {
       String s = (String) map.get(IBreakpoints.STATUS_ERROR);
       if (s != null && error == null) error = s;
       Object planted = map.get(IBreakpoints.STATUS_INSTANCES);
       if (planted != null) {
         Collection<Map<String, Object>> list = (Collection<Map<String, Object>>) planted;
         for (Map<String, Object> m : list) {
           if (m.get(IBreakpoints.INSTANCE_ERROR) == null) {
             return "Planted";
           }
         }
       }
     }
   }
   return error;
 }
Пример #23
0
  public void testSetAndReset() throws InterruptedException, ExecutionException {
    fTestCache =
        new TestCache() {
          @Override
          protected void handleCompleted(Integer data, Throwable error, boolean canceled) {
            if (!canceled) {
              // USE 'false' for valid argument.  Cache should be left in
              // invalid state.
              set(data, error, false);
            }
          }
        };

    // Request data from cache
    Query<Integer> q = new TestQuery();
    q.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    // Query should complete with the data from request monitor.
    try {
      q.get();
      Assert.fail("Expected InvalidCacheException");
    } catch (ExecutionException e) {
    }

    // No need to disable cache, it should already be disabled.

    // Check final state
    assertCacheResetWithoutData();
  }
Пример #24
0
 /* (non-Javadoc)
  * @see org.eclipse.tcf.te.runtime.properties.PropertiesContainer#checkThreadAccess()
  */
 @Override
 protected final boolean checkThreadAccess() {
   return Protocol.isDispatchThread();
 }
Пример #25
0
  /**
   * This test forces a race condition where a client that requested data cancels. While shortly
   * after a second client starts a new request. The first request's cancel should not interfere
   * with the second request.
   */
  public void testCancelAfterCompletedRaceCondition()
      throws InterruptedException, ExecutionException {

    // Create a client request with a badly behaved cancel implementation.
    final Callback[] rmBad = new Callback[1];
    final boolean qBadCanceled[] = new boolean[] {false};
    Query<Integer> qBad =
        new Query<Integer>() {
          @Override
          protected void execute(final DataCallback<Integer> rm) {
            rmBad[0] =
                new Callback(rm) {
                  @Override
                  public synchronized void removeCancelListener(ICanceledListener listener) {
                    // Do not add the cancel listener so that the cancel request is not
                    // propagated to the cache.
                  }

                  @Override
                  public void cancel() {
                    if (qBadCanceled[0]) {
                      super.cancel();
                    }
                  }

                  @Override
                  public synchronized boolean isCanceled() {
                    return qBadCanceled[0];
                  }

                  @Override
                  public synchronized void done() {
                    // Avoid clearing cancel listeners list
                  };

                  @Override
                  protected void handleSuccess() {
                    rm.setData(fTestCache.getData());
                    rm.done();
                  };
                };

            fTestCache.wait(rmBad[0]);
          }
        };
    qBad.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Reset the cache
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm = null;
            fTestCache.set(null, null, true);
            fTestCache.reset();
          }
        });

    Query<Integer> qGood = new TestQuery();
    qGood.invoke();

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    qBadCanceled[0] = true;
    rmBad[0].cancel();

    Assert.assertFalse(fRetrieveRm.isCanceled());

    // Completed the retrieve RM
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    qGood.get();

    assertCacheValidWithData(1);
  }
Пример #26
0
  private void updateAnnotations(final IWorkbenchWindow window, final TCFNode node) {
    if (disposed) return;
    assert Thread.currentThread() == display.getThread();
    final WorkbenchWindowInfo win_info = windows.get(window);
    if (win_info == null) return;
    ITCFAnnotationProvider provider = TCFAnnotationProvider.getAnnotationProvider(node);
    if (win_info.provider != provider) {
      if (win_info.provider != null) win_info.provider.updateAnnotations(window, null);
      win_info.provider = provider;
    }
    if (win_info.provider != null) {
      if (win_info.annotations.size() > 0) {
        for (TCFAnnotation a : win_info.annotations) a.dispose();
        win_info.annotations.clear();
      }
      win_info.update_node = node;
      win_info.update_task = null;
      win_info.provider.updateAnnotations(window, node);
      return;
    }
    if (win_info.update_node == node && win_info.update_task != null && !win_info.update_task.done)
      return;
    win_info.update_node = node;
    win_info.update_task =
        new UpdateTask() {
          public void run() {
            if (win_info.update_task != this) {
              /* Selection has changed and another update has started - abort this */
              return;
            }
            if (node == null) {
              /* No selection - no annotations */
              done(null);
              return;
            }
            if (node.isDisposed()) {
              /* Selected node disposed - no annotations */
              done(null);
              return;
            }
            TCFNodeExecContext thread = null;
            TCFNodeExecContext memory = null;
            TCFNodeStackFrame frame = null;
            TCFNodeStackFrame last_top_frame = null;
            String bp_group = null;
            boolean suspended = false;
            if (node instanceof TCFNodeStackFrame) {
              thread = (TCFNodeExecContext) node.parent;
              frame = (TCFNodeStackFrame) node;
              // Make sure frame.getFrameNo() is valid
              TCFChildrenStackTrace trace = thread.getStackTrace();
              if (!trace.validate(this)) return;
            } else if (node instanceof TCFNodeExecContext) {
              thread = (TCFNodeExecContext) node;
              // Make sure frame.getTopFrame() is valid
              TCFChildrenStackTrace trace = thread.getStackTrace();
              if (!trace.validate(this)) return;
              frame = trace.getTopFrame();
            }
            if (thread != null) {
              TCFDataCache<IRunControl.RunControlContext> rc_ctx_cache = thread.getRunContext();
              if (!rc_ctx_cache.validate(this)) return;
              IRunControl.RunControlContext rc_ctx_data = rc_ctx_cache.getData();
              if (rc_ctx_data != null) bp_group = rc_ctx_data.getBPGroup();
              TCFDataCache<TCFNodeExecContext> mem_cache = thread.getMemoryNode();
              if (!mem_cache.validate(this)) return;
              memory = mem_cache.getData();
              if (bp_group == null
                  && memory != null
                  && rc_ctx_data != null
                  && rc_ctx_data.hasState()) bp_group = memory.id;
              last_top_frame = thread.getLastTopFrame();
              TCFDataCache<TCFContextState> state_cache = thread.getState();
              if (!state_cache.validate(this)) return;
              suspended = state_cache.getData() != null && state_cache.getData().is_suspended;
            }
            Set<TCFAnnotation> set = new LinkedHashSet<TCFAnnotation>();
            if (memory != null) {
              TCFLaunch launch = node.launch;
              TCFBreakpointsStatus bs = launch.getBreakpointsStatus();
              if (bs != null) {
                for (String id : bs.getStatusIDs()) {
                  Map<String, Object> map = bs.getStatus(id);
                  if (map == null) continue;
                  String error = (String) map.get(IBreakpoints.STATUS_ERROR);
                  if (error != null)
                    addBreakpointErrorAnnotation(set, launch, memory.id, id, error);
                  Object[] arr = toObjectArray(map.get(IBreakpoints.STATUS_INSTANCES));
                  if (arr == null) continue;
                  for (Object o : arr) {
                    Map<String, Object> m = toObjectMap(o);
                    String ctx_id = (String) m.get(IBreakpoints.INSTANCE_CONTEXT);
                    if (ctx_id == null) continue;
                    if (!ctx_id.equals(node.id) && !ctx_id.equals(bp_group)) continue;
                    error = (String) m.get(IBreakpoints.INSTANCE_ERROR);
                    BigInteger addr =
                        JSON.toBigInteger((Number) m.get(IBreakpoints.INSTANCE_ADDRESS));
                    ILineNumbers.CodeArea area = null;
                    ILineNumbers.CodeArea org_area = getBreakpointCodeArea(launch, id);
                    if (addr != null) {
                      TCFDataCache<TCFSourceRef> line_cache = memory.getLineInfo(addr);
                      if (line_cache != null) {
                        if (!line_cache.validate(this)) return;
                        TCFSourceRef line_data = line_cache.getData();
                        if (line_data != null) area = line_data.area;
                      }
                    }
                    if (area == null) area = org_area;
                    String bp_name = "Breakpoint";
                    IBreakpoint bp = TCFBreakpointsModel.getBreakpointsModel().getBreakpoint(id);
                    if (bp != null)
                      bp_name =
                          bp.getMarker().getAttribute(TCFBreakpointsModel.ATTR_MESSAGE, bp_name);
                    if (error != null) {
                      String location = "";
                      if (addr != null) location = " at 0x" + addr.toString(16);
                      if (org_area == null) org_area = area;
                      TCFAnnotation a =
                          new TCFAnnotation(
                              memory.id,
                              id,
                              addr,
                              org_area,
                              ImageCache.IMG_BREAKPOINT_ERROR,
                              bp_name + " failed to plant" + location + ": " + error,
                              TYPE_BP_INSTANCE);
                      set.add(a);
                    } else if (area != null && addr != null) {
                      String location =
                          " planted at 0x" + addr.toString(16) + ", line " + area.start_line;
                      TCFAnnotation a =
                          new TCFAnnotation(
                              memory.id,
                              id,
                              addr,
                              area,
                              ImageCache.IMG_BREAKPOINT_INSTALLED,
                              bp_name + location,
                              TYPE_BP_INSTANCE);
                      a.breakpoint = bp;
                      set.add(a);
                      if (isLineAdjusted(area, org_area)) {
                        TCFAnnotation b =
                            new TCFAnnotation(
                                memory.id,
                                id,
                                null,
                                org_area,
                                ImageCache.IMG_BREAKPOINT_WARNING,
                                "Breakpoint location is adjusted: " + location,
                                TYPE_BP_INSTANCE);
                        set.add(b);
                      }
                    }
                    error = (String) m.get(IBreakpoints.INSTANCE_CONDITION_ERROR);
                    if (error != null) {
                      TCFAnnotation a =
                          new TCFAnnotation(
                              memory.id,
                              id,
                              addr,
                              org_area,
                              ImageCache.IMG_BREAKPOINT_ERROR,
                              bp_name + " failed to evaluate condition: " + error,
                              TYPE_BP_INSTANCE);
                      set.add(a);
                    }
                  }
                }
              }
            }
            if (suspended && frame != null && frame.getFrameNo() >= 0) {
              TCFDataCache<TCFSourceRef> line_cache = frame.getLineInfo();
              if (!line_cache.validate(this)) return;
              TCFSourceRef line_data = line_cache.getData();
              if (line_data != null && line_data.area != null) {
                TCFAnnotation a = null;
                String addr_str = "";
                TCFDataCache<BigInteger> addr_cache = frame.getAddress();
                if (!addr_cache.validate(this)) return;
                BigInteger addr_data = addr_cache.getData();
                if (addr_data != null) addr_str += ", IP: 0x" + addr_data.toString(16);
                TCFDataCache<IStackTrace.StackTraceContext> frame_cache =
                    frame.getStackTraceContext();
                if (!frame_cache.validate(this)) return;
                IStackTrace.StackTraceContext frame_data = frame_cache.getData();
                if (frame_data != null) {
                  BigInteger i = JSON.toBigInteger(frame_data.getFrameAddress());
                  if (i != null) addr_str += ", FP: 0x" + i.toString(16);
                }
                addr_str += ", line: " + line_data.area.start_line;
                if (frame.getFrameNo() == 0) {
                  a =
                      new TCFAnnotation(
                          line_data.context_id,
                          null,
                          null,
                          line_data.area,
                          ImageCache.IMG_INSTRUCTION_POINTER_TOP,
                          "Current Instruction Pointer" + addr_str,
                          TYPE_TOP_FRAME);
                } else {
                  a =
                      new TCFAnnotation(
                          line_data.context_id,
                          null,
                          null,
                          line_data.area,
                          ImageCache.IMG_INSTRUCTION_POINTER,
                          "Call Stack Frame" + addr_str,
                          TYPE_STACK_FRAME);
                }
                set.add(a);
              }
            }
            if (!suspended && last_top_frame != null) {
              TCFDataCache<TCFSourceRef> line_cache = last_top_frame.getLineInfo();
              if (!line_cache.validate(this)) return;
              TCFSourceRef line_data = line_cache.getData();
              if (line_data != null && line_data.area != null) {
                TCFAnnotation a =
                    new TCFAnnotation(
                        line_data.context_id,
                        null,
                        null,
                        line_data.area,
                        ImageCache.IMG_INSTRUCTION_POINTER,
                        "Last Instruction Pointer position",
                        TYPE_STACK_FRAME);
                set.add(a);
              }
            }
            done(set);
          }

          private void done(final Set<TCFAnnotation> res) {
            done = true;
            final Runnable update_task = this;
            displayExec(
                new Runnable() {
                  public void run() {
                    if (update_task != win_info.update_task) return;
                    assert win_info.update_node == node;
                    win_info.update_task = null;
                    try {
                      ResourcesPlugin.getWorkspace()
                          .run(
                              new IWorkspaceRunnable() {
                                public void run(IProgressMonitor monitor) throws CoreException {
                                  updateAnnotations(window, node, res);
                                }
                              },
                              null);
                    } catch (Exception e) {
                      Activator.log(e);
                    }
                  }
                });
          }
        };
    Protocol.invokeLater(win_info.update_task);
  }
Пример #27
0
  public void testCancelWhilePendingWithManyClients()
      throws InterruptedException, ExecutionException {
    // Request data from cache
    List<Query<Integer>> qList = new ArrayList<Query<Integer>>();
    for (int i = 0; i < 10; i++) {
      Query<Integer> q = new TestQuery();
      q.invoke();
      Protocol.invokeAndWait(
          new Runnable() {
            public void run() {}
          });
      qList.add(q);
    }

    // Wait until the cache starts data retrieval.
    waitForRetrieveRm();

    // Cancel some client requests
    int[] toCancel = new int[] {0, 2, 5, 9};
    for (int i = 0; i < toCancel.length; i++) {

      // Cancel request and verify that its canceled
      Query<Integer> q = qList.get(toCancel[i]);
      q.cancel(true);
      try {
        q.get();
        Assert.fail("Expected a cancellation exception");
      } catch (CancellationException e) {
      } // Expected exception;
      qList.set(toCancel[i], null);

      assertCacheWaiting();
    }

    // Replace canceled requests with new ones
    for (int i = 0; i < toCancel.length; i++) {
      Query<Integer> q = new TestQuery();
      q.invoke();
      Protocol.invokeAndWait(
          new Runnable() {
            public void run() {}
          });
      qList.set(toCancel[i], q);
      assertCacheWaiting();
    }

    // Now cancel all requests
    for (int i = 0; i < (qList.size() - 1); i++) {
      // Validate that cache is still waiting and is not canceled
      assertCacheWaiting();
      qList.get(i).cancel(true);
    }
    qList.get(qList.size() - 1).cancel(true);
    assertCacheInvalidAndWithCanceledRM();

    // Completed the retrieve RM
    Protocol.invokeAndWait(
        new Runnable() {
          public void run() {
            fRetrieveRm.setData(1);
            fRetrieveRm.done();
          }
        });

    // Validate that cache didn't accept the result after its RM was canceled
    assertCacheInvalidAndWithCanceledRM();
  }
Пример #28
0
 @Override
 public void onDisconnected(final TCFLaunch launch) {
   assert Protocol.isDispatchThread();
   updateAnnotations(null, launch);
 }
Пример #29
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.viewers.ITreeViewerListener#treeExpanded(org.eclipse.jface.viewers.TreeExpansionEvent)
   */
  @Override
  public void treeExpanded(TreeExpansionEvent event) {
    // Get the expanded element
    Object element = event.getElement();
    if (element instanceof IProcessContextNode) {
      final IProcessContextNode node = (IProcessContextNode) element;

      // Flag that tells if the node shall be refreshed
      boolean needsRefresh = false;

      // Get the asynchronous refresh context adapter
      final IAsyncRefreshableCtx refreshable =
          (IAsyncRefreshableCtx) node.getAdapter(IAsyncRefreshableCtx.class);
      Assert.isNotNull(refreshable);
      // The node needs to be refreshed if the child list query is not done
      if (refreshable.getQueryState(QueryType.CHILD_LIST).equals(QueryState.PENDING)) {
        needsRefresh = true;
      } else if (refreshable.getQueryState(QueryType.CHILD_LIST).equals(QueryState.DONE)) {
        // Our policy is that the current node and it's level 1 children are always
        // fully refreshed. The child list query for the current node is not pending,
        // so check the children nodes if they need a refresh
        for (final IProcessContextNode candidate : node.getChildren(IProcessContextNode.class)) {
          // Get the asynchronous refresh context adapter
          final IAsyncRefreshableCtx r =
              (IAsyncRefreshableCtx) candidate.getAdapter(IAsyncRefreshableCtx.class);
          Assert.isNotNull(r);
          // If the child list query state is still pending, set the flag and break out of the loop
          if (r.getQueryState(QueryType.CHILD_LIST).equals(QueryState.PENDING)) {
            needsRefresh = true;
            break;
          }
        }
      }

      // If the node needs to be refreshed, refresh it now.
      if (needsRefresh) {
        // Mark the refresh as in progress
        refreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
        // Create a new pending operation node and associate it with the refreshable
        PendingOperationModelNode pendingNode = new PendingOperationNode();
        pendingNode.setParent(node);
        refreshable.setPendingOperationNode(pendingNode);

        Runnable runnable =
            new Runnable() {
              @Override
              public void run() {
                // Trigger a refresh of the view content.
                ChangeEvent ev =
                    new ChangeEvent(node, IContainerModelNode.NOTIFY_CHANGED, null, null);
                EventManager.getInstance().fireEvent(ev);

                // Get the parent model of the node
                IModel model = node.getParent(IModel.class);
                Assert.isNotNull(model);

                // Don't send change events while refreshing
                final boolean changed = node.setChangeEventsEnabled(false);
                // Initiate the refresh
                model
                    .getService(IModelRefreshService.class)
                    .refresh(
                        node,
                        new Callback() {
                          @Override
                          protected void internalDone(Object caller, IStatus status) {
                            // Mark the refresh as done
                            refreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
                            // Reset the pending operation node
                            refreshable.setPendingOperationNode(null);
                            // Re-enable the change events if they had been enabled before
                            if (changed) node.setChangeEventsEnabled(true);
                            // Trigger a refresh of the view content
                            ChangeEvent event =
                                new ChangeEvent(
                                    node, IContainerModelNode.NOTIFY_CHANGED, null, null);
                            EventManager.getInstance().fireEvent(event);
                          }
                        });
              }
            };

        Protocol.invokeLater(runnable);
      }
    }
  }
Пример #30
0
  /* (non-Javadoc)
   * @see org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistableURIProvider#getURI(java.lang.Object)
   */
  @Override
  public URI getURI(final Object context) {
    Assert.isNotNull(context);

    URI uri = null;
    final IPeer peer = getPeer(context);

    if (peer != null) {
      // Get the URI the peer model has been created from
      final AtomicReference<URI> nodeURI = new AtomicReference<URI>();
      final AtomicReference<Version> version = new AtomicReference<Version>();
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              String value = peer.getAttributes().get(IPersistableNodeProperties.PROPERTY_URI);
              if (value != null && !"".equals(value.trim())) { // $NON-NLS-1$
                nodeURI.set(URI.create(value.trim()));
              }
              value = peer.getAttributes().get(IPeerProperties.PROP_VERSION);
              version.set(value != null ? new Version(value.trim()) : null);
            }
          };
      if (Protocol.isDispatchThread()) {
        runnable.run();
      } else {
        Protocol.invokeAndWait(runnable);
      }

      if (nodeURI.get() != null) {
        uri = nodeURI.get();
      }

      if (uri == null) {
        String baseName = peer.getName();
        if (baseName == null) {
          baseName = peer.getID();
        }
        String name = makeValidFileSystemName(baseName);
        // Get the URI from the name
        uri = getRoot().append(name + ".peer").toFile().toURI(); // $NON-NLS-1$
        try {
          File file = new File(uri.normalize());
          int i = 0;
          while (file.exists()) {
            name =
                makeValidFileSystemName(
                    baseName
                        + (version.get() != null ? "_" + version.get().toString() : "")
                        + //$NON-NLS-1$ //$NON-NLS-2$
                        (i > 0 ? " (" + i + ")" : "")); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            uri = getRoot().append(name + ".peer").toFile().toURI(); // $NON-NLS-1$
            file = new File(uri.normalize());
            i++;
          }
        } catch (Exception e) {
        }
      }
    }

    return uri;
  }