protected final synchronized void unsubscribeTenant(String tenantId, String reason)
     throws IOException {
   Preconditions.checkState(
       tenantConfig.eventBusMap().containsKey(tenantId),
       "Cannot unsubscribe %s tenant '%s' (reason: %s) because EventBus not found. %s available: %s",
       getClass().getName(),
       tenantId,
       reason,
       tenantConfig.eventBusMap().size(),
       tenantConfig.eventBusMap().keySet());
   final EventBus tenantEventBus = tenantConfig.eventBusMap().get(tenantId);
   Preconditions.checkState(
       subscriberMap.containsKey(tenantId),
       "Cannot unsubscribe %s tenant '%s' (reason: %s) because subscribers not found, createSubscribers() never called? %s available: %s",
       getClass().getName(),
       tenantId,
       reason,
       subscriberMap.size(),
       subscriberMap.keySet());
   final List<Object> subscribers = subscriberMap.get(tenantId);
   log.debug(
       "Unsubscribing {} objects from '{}' EventBus: {}. Reason: {}",
       subscribers.size(),
       tenantId,
       subscribers,
       reason);
   for (Object subscriber : subscribers) {
     tenantEventBus.unregister(subscriber);
   }
   subscriberMap.remove(tenantId);
 }
Exemplo n.º 2
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testMonitorAndContinueWithoutTimeout() {
    ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class);
    ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class);
    expect(
            schedulerMock.scheduleWithFixedDelay(
                anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class)))
        .andReturn(mockFuture);

    replay(mockFuture);
    replay(schedulerMock);

    CoutingEventHandler handler = new CoutingEventHandler();
    EventBus eventBus = new EventBus();
    eventBus.register(handler);

    AsyncMonitor<Object> monitor =
        mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.CONTINUE), eventBus);

    assertNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.startMonitoring(null);
    assertNotNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.run();
    assertEquals(handler.numCompletes, 0);
    assertEquals(handler.numFailures, 0);
    assertEquals(handler.numTimeouts, 0);

    verify(mockFuture);
    verify(schedulerMock);
  }
Exemplo n.º 3
0
 @Test
 public void insertionDelayIsForwardedToSoneInserter() {
   EventBus eventBus = new AsyncEventBus(sameThreadExecutor());
   eventBus.register(new SoneInserter(core, eventBus, freenetInterface, "SoneId"));
   eventBus.post(new InsertionDelayChangedEvent(15));
   assertThat(SoneInserter.getInsertionDelay().get(), is(15));
 }
 protected final synchronized void createSubscribers(
     String tenantId, AppManifest appManifest, String reason) {
   @Nullable final List<Object> existing = subscriberMap.get(tenantId);
   Preconditions.checkState(
       existing == null,
       "%s subscribers for '%s' already exists with %s existing subscribers, probably wasn't stopped properly",
       getClass().getName(),
       tenantId,
       existing != null ? existing.size() : null);
   try (Closeable cl = CommandRequestAttributes.withMdc(tenantId)) {
     final List<?> subscribers = onReady(tenantId, appManifest);
     log.debug(
         "Subscribing {} objects to '{}' EventBus: {}. Reason: {}",
         subscribers.size(),
         tenantId,
         subscribers,
         reason);
     final EventBus tenantEventBus = tenantConfig.eventBusMap().get(tenantId);
     subscriberMap.put(tenantId, ImmutableList.copyOf(subscribers));
     for (Object subscriber : subscribers) {
       tenantEventBus.register(subscriber);
     }
   } catch (Exception e) {
     throw new TenantException(
         "Cannot create EventBus subscribers for tenant '" + tenantId + "' reason " + reason + ".",
         e);
   }
 }
Exemplo n.º 5
0
 @Override
 public ExecResponse call() {
   checkState(ssh != null, "please call init() before invoking call");
   try {
     ssh.connect();
     ExecResponse returnVal;
     eventBus.post(new StatementOnNodeSubmission(statement, node));
     String command =
         runAsRoot
             ? execAsRoot(statement.render(OsFamily.UNIX))
             : execScriptAsDefaultUser(statement.render(OsFamily.UNIX));
     try {
       returnVal = runCommand(command);
     } catch (Throwable e) {
       eventBus.post(new StatementOnNodeFailure(statement, node, e));
       throw Throwables.propagate(e);
     }
     eventBus.post(new StatementOnNodeCompletion(statement, node, returnVal));
     if (logger.isTraceEnabled()) logger.trace("<< %s[%s]", statement, returnVal);
     else logger.debug("<< %s(%d)", statement, returnVal.getExitStatus());
     return returnVal;
   } finally {
     if (ssh != null) ssh.disconnect();
   }
 }
Exemplo n.º 6
0
  @Test
  public void testTick() {
    IMocksControl control = createControl();

    GregorianCalendar startDateMock = control.createMock(GregorianCalendar.class);
    GregorianCalendar startDateCloneMock = control.createMock(GregorianCalendar.class);
    expect(startDateMock.clone()).andReturn(startDateCloneMock).once();
    GregorianCalendar currentDateCloneMock = control.createMock(GregorianCalendar.class);
    expect(startDateCloneMock.clone()).andReturn(currentDateCloneMock).once();

    startDateCloneMock.add(Calendar.DAY_OF_MONTH, 1);

    EventBus eventBusMock = control.createMock(EventBus.class);
    eventBusMock.post(anyObject(TimeTickEvent.class));
    expectLastCall().once();

    control.replay();

    TimeManagerImpl manager =
        new TimeManagerImpl(startDateMock, Calendar.DAY_OF_MONTH, 1, eventBusMock);
    Calendar newDate = manager.tick();

    assertEquals(startDateCloneMock, newDate);

    control.verify();
  }
Exemplo n.º 7
0
  @Test
  public void testSocketPreview() {
    SocketHint<Number> sh = SocketHints.createNumberSocketHint("foo", 0);
    OutputSocket<Number> socket = new OutputSocketImpl<>(eventBus, sh);

    final boolean[] handled = new boolean[] {false};
    Object eventHandler =
        new Object() {
          @SuppressFBWarnings(
              value = "UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS",
              justification = "This method is called by Guava's EventBus")
          @Subscribe
          public void onSocketPreviewed(SocketPreviewChangedEvent e) {
            handled[0] = true;
            assertTrue(
                "A preview event fired for a socket but the socket was not labeled as able to "
                    + "be previewed",
                socket.isPreviewed());
          }
        };

    eventBus.register(eventHandler);
    socket.setPreviewed(true);
    eventBus.unregister(eventHandler);

    assertTrue("SocketPreviewChangedEvent was not received", handled[0]);
  }
 @Override
 public void onScaleEnd(ScaleGestureDetector detector) {
   if (detector.getScaleFactor() < 1f) {
     bus.post(Pinch.INSTANCE);
   } else {
     bus.post(Zoom.INSTANCE);
   }
 }
 @Override
 public boolean onFling(MotionEvent a, MotionEvent b, float velocity, float _) {
     if (Math.abs(a.getY() - b.getY()) > MAXIMUM_OFFSET) {
         return false;
     } else if (isLeftOf(a, b, velocity)) {
         bus.post(LeftFling.INSTANCE);
         return true;
     } else if (isLeftOf(b, a, velocity)) {
         bus.post(RightFling.INSTANCE);
         return true;
     } else {
         return false;
     }
 }
Exemplo n.º 10
0
 @Override
 public Object postProcessAfterInitialization(final Object bean, final String beanName)
     throws BeansException {
   log.trace(Scope.SYSTEM.marker(), "event bus registration of {}({})", beanName, bean.getClass());
   eventBus.register(bean);
   return bean;
 }
Exemplo n.º 11
0
  @Override
  protected void configure() {
    final EventBus eventBus = new AsyncEventBus(Executors.newCachedThreadPool());
    eventBus.register(new DeadEventListener());
    bind(EventBus.class).toInstance(eventBus);

    bind(VideoRecorder.class).to(FFmpegRecorder.class);
    bind(VideoStreamer.class).to(FFmpegStreamer.class);
    bind(VideoFacade.class).to(VideoFacadeImpl.class).in(Scopes.SINGLETON);
    bind(Config.class).in(Scopes.SINGLETON);

    bind(CommandServer.class).asEagerSingleton();
    bind(Monitor.class).annotatedWith(Names.named("DiskSpace")).to(MonitorDiskSpace.class);
    bind(Monitor.class).annotatedWith(Names.named("RecordingSize")).to(MonitorRecordingSize.class);
    bind(MonitorManager.class);
  }
Exemplo n.º 12
0
 public static void sendEvent(Object event) {
   if (eventBus != null) {
     eventBus.post(event);
   } else {
     LOGGER.warning("No event bus available");
   }
 }
Exemplo n.º 13
0
 private void removeElement(JournalElement elt) {
   setCurrentEltAndGrp(elt, elt.getGroup());
   elt.removeFromGroup();
   elementDeletedList.add(elt.getId());
   if (request.isXHR()) ajaxResponseRenderer.addRender(elementZone);
   eventBusRecorder.post(new JournalDeleteEvent(elt));
 }
Exemplo n.º 14
0
  protected void addDataPoint(String s) throws InvalidDataPointException {
    ArrayList<SDataPoint> arDP = SDataPointHelper.createDataPoint(s, m_swConfiguration);

    for (SDataPoint dp : arDP) {
      m_eventBus.post(dp);
    }
  }
 /**
  * If you want to handle event sent to the channel, you can initialize the bus with custom handler
  *
  * @param addr
  * @param addrSync
  * @param busHandler custom handler instance, which intercept the event. The method which handle
  *     the bus event must be annotate with "@Subscribe"
  */
 public BusGuavaImpl(final String addr, final String addrSync, final List<Object> busHandler) {
   new BusGuavaImpl(addr, addrSync);
   for (Object handler : busHandler) {
     channel.register(handler);
     logger.info("handler={} is registered to the channel={}", handler, CHANNEL_NAME);
   }
 }
Exemplo n.º 16
0
 private void httpRequestReceived(HttpRequest request, Channel channel) {
   HttpResponse response = getResponse(request);
   eventBus.post(response);
   channel.write(response);
   channel.disconnect();
   channel.close();
 }
Exemplo n.º 17
0
 public void stopSession() {
   tracker.stopTracking(getSession());
   locationHelper.stop();
   state.recording().stopRecording();
   notificationHelper.hideRecordingNotification();
   eventBus.post(new SessionStoppedEvent(getSession()));
 }
  @Override
  protected void shutDown() throws Exception {
    LOG.debug("Stopping InputSetupService");
    eventBus.unregister(this);

    for (InputState state : inputRegistry.getRunningInputs()) {
      MessageInput input = state.getMessageInput();

      LOG.info(
          "Attempting to close input <{}> [{}].", input.getUniqueReadableId(), input.getName());

      Stopwatch s = Stopwatch.createStarted();
      try {
        input.stop();

        LOG.info(
            "Input <{}> closed. Took [{}ms]",
            input.getUniqueReadableId(),
            s.elapsed(TimeUnit.MILLISECONDS));
      } catch (Exception e) {
        LOG.error(
            "Unable to stop input <{}> [{}]: " + e.getMessage(),
            input.getUniqueReadableId(),
            input.getName());
      } finally {
        s.stop();
      }
    }
    LOG.debug("Stopped InputSetupService");
  }
Exemplo n.º 19
0
 @Subscribe
 public void onEvent(ModelArchiveDownloadedEvent e) throws IOException {
   if (!isRunning()) {
     log(INFO_SERVICE_NOT_RUNNING);
     return;
   }
   if (isIndex(e.model)) {
     File location = repository.getLocation(e.model, false).orNull();
     String remoteUri = e.model.getHint(HINT_REPOSITORY_URL).orNull();
     if (remoteUri != null) {
       Pair<File, IModelIndex> pair = openDelegates.get(remoteUri);
       if (pair == null) {
         File folder = createIndexLocation(remoteUri);
         folder.mkdir();
         Zips.unzip(location, folder);
         openDelegate(remoteUri, folder);
       } else {
         File folder = Files.createTempDir();
         Zips.unzip(location, folder);
         IModelIndex modelIndex = pair.getSecond();
         modelIndex.updateIndex(folder);
         bus.post(new ModelIndexOpenedEvent());
         FileUtils.deleteDirectory(folder);
       }
     }
   }
 }
 /**
  * Default bus initialization with only one handler, the default publisher
  *
  * @param addr
  * @param addrSync
  */
 public BusGuavaImpl(final String addr, final String addrSync) {
   Publisher pub = new PublisherZMQImpl();
   pub.open(addr, addrSync);
   channel.register(pub);
   logger.info(
       "Bus initialized (publisher open with address={} and synchronization address={}, and publisher register to the channel={})",
       new Object[] {addr, addrSync, CHANNEL_NAME});
 }
Exemplo n.º 21
0
 public void onEditElement(String eltId, String gpId) {
   JournalElement elt = getElementFromGroup(eltId, getGroupFromGroupsList(gpId));
   group = elt.getGroup();
   element = elt;
   eventBusRecorder.post(new JournalEditEvent(elt));
   elementEditedId = element.getId();
   if (request.isXHR()) ajaxResponseRenderer.addRender(journalZone);
 }
Exemplo n.º 22
0
 private HttpResponse getResponse(HttpRequest request) {
   try {
     return doGetHttpResponse(request);
   } catch (Exception e) {
     eventBus.post(e);
     return DEFAULT_HTTP_RESPONSE;
   }
 }
Exemplo n.º 23
0
  /**
   * Helper for differential analysis which aggregates the TestSummary for an individual target,
   * reporting runs on the EventBus if necessary.
   */
  private TestSummary.Builder aggregateAndReportSummary(
      ConfiguredTarget testTarget, AggregatingTestListener listener) {

    // If already reported by the listener, no work remains for this target.
    TestSummary.Builder summary = listener.getCurrentSummary(testTarget);
    Label testLabel = testTarget.getLabel();
    Preconditions.checkNotNull(
        summary, "%s did not complete test filtering, but has a test result", testLabel);
    if (listener.targetReported(testTarget)) {
      return summary;
    }

    Collection<Artifact> incompleteRuns = listener.getIncompleteRuns(testTarget);
    Map<Artifact, TestResult> statusMap = listener.getStatusMap();

    // We will get back multiple TestResult instances if test had to be retried several
    // times before passing. Sharding and multiple runs of the same test without retries
    // will be represented by separate artifacts and will produce exactly one TestResult.
    for (Artifact testStatus : TestProvider.getTestStatusArtifacts(testTarget)) {
      // When a build is interrupted ( eg. a broken target with --nokeep_going ) runResult could
      // be null for an unrelated test because we were not able to even try to execute the test.
      // In that case, for tests that were previously passing we return null ( == NO STATUS),
      // because checking if the cached test target is up-to-date would require running the
      // dependency checker transitively.
      TestResult runResult = statusMap.get(testStatus);
      boolean isIncompleteRun = incompleteRuns.contains(testStatus);
      if (runResult == null) {
        summary = markIncomplete(summary);
      } else if (isIncompleteRun) {
        // Only process results which were not recorded by the listener.

        boolean newlyFetched = !statusMap.containsKey(testStatus);
        summary = incrementalAnalyze(summary, runResult);
        if (newlyFetched) {
          eventBus.post(runResult);
        }
        Preconditions.checkState(
            listener.getIncompleteRuns(testTarget).contains(testStatus) == isIncompleteRun,
            "TestListener changed in differential analysis. Ensure it isn't still registered.");
      }
    }

    // The target was not posted by the listener and must be posted now.
    eventBus.post(summary.build());
    return summary;
  }
Exemplo n.º 24
0
 public void distributeStateMessage(Class<?> customEvent) {
   try {
     masterChannel.post(customEvent.newInstance());
   } catch (Exception e) {
     FMLLog.log(Level.SEVERE, e, "An unexpected exception");
     throw new LoaderException(e);
   }
 }
Exemplo n.º 25
0
  private void innerBroadcast(MessageContext ctx) {
    EventBus carryEventBus = this.getContext().getCarryEventBus();

    BroadcastEventProcessor eventProcessor = new BroadcastEventProcessor();
    carryEventBus.register(eventProcessor);

    CommonEventProcessor.MsgIdGenerateEvent msgIdGenerateEvent =
        new CommonEventProcessor.MsgIdGenerateEvent();
    BroadcastEventProcessor.ValidateEvent validateEvent =
        new BroadcastEventProcessor.ValidateEvent();
    BroadcastEventProcessor.PermissionCheckEvent permissionCheckEvent =
        new BroadcastEventProcessor.PermissionCheckEvent();
    BroadcastEventProcessor.BroadcastEvent broadcastEvent =
        new BroadcastEventProcessor.BroadcastEvent();

    msgIdGenerateEvent.setMessageContext(ctx);
    validateEvent.setMessageContext(ctx);
    permissionCheckEvent.setMessageContext(ctx);
    broadcastEvent.setMessageContext(ctx);

    carryEventBus.post(msgIdGenerateEvent);
    carryEventBus.post(validateEvent);
    carryEventBus.post(permissionCheckEvent);
    carryEventBus.post(broadcastEvent);

    carryEventBus.unregister(eventProcessor);
  }
Exemplo n.º 26
0
 @BeginRender
 public void initialize() {
   if (summaryList == null) summaryList = Lists.newArrayList();
   if (elementDeletedList == null) elementDeletedList = Lists.newArrayList();
   if (eventBusListener == null) {
     eventBusListener = new EventBus();
     eventBusListener.register(this);
   }
 }
  @Override
  public void deleteDocument(String docId, String prevRevId) throws ConflictException {
    Preconditions.checkState(this.isOpen(), "Database is closed");
    Preconditions.checkArgument(
        !Strings.isNullOrEmpty(docId), "Input document id can not be empty");
    Preconditions.checkArgument(
        !Strings.isNullOrEmpty(prevRevId), "Input previous revision id can not be empty");

    CouchUtils.validateRevisionId(prevRevId);

    DocumentDeleted documentDeleted = null;
    this.sqlDb.beginTransaction();
    try {
      BasicDocumentRevision preRevision = this.getDocument(docId, prevRevId);
      if (preRevision == null) {
        throw new IllegalArgumentException("The document trying to update does not exist.");
      }

      DocumentRevisionTree revisionTree = this.getAllRevisionsOfDocument(docId);
      if (revisionTree == null) {
        throw new IllegalArgumentException("Document does not exist for id: " + docId);
      } else if (!revisionTree.leafRevisionIds().contains(prevRevId)) {
        throw new ConflictException("Revision to be deleted is not a leaf node:" + prevRevId);
      }

      if (!preRevision.isDeleted()) {
        this.checkOffPreviousWinnerRevisionStatus(preRevision);
        String newRevisionId = CouchUtils.generateNextRevisionId(preRevision.getRevision());
        // Previous revision to be deleted could be winner revision ("current" == true),
        // or a non-winner leaf revision ("current" == false), the new inserted
        // revision must have the same flag as it previous revision.
        // Deletion of non-winner leaf revision is mainly used when resolving
        // conflicts.
        this.insertRevision(
            preRevision.getInternalNumericId(),
            newRevisionId,
            preRevision.getSequence(),
            true,
            preRevision.isCurrent(),
            JSONUtils.EMPTY_JSON,
            false);
        BasicDocumentRevision newRevision = this.getDocument(preRevision.getId(), newRevisionId);
        documentDeleted = new DocumentDeleted(preRevision, newRevision);
      }

      // Very tricky! Must call setTransactionSuccessful() even no change
      // to the db within this method. This is to allow this method to be
      // nested to other outer transaction, otherwise, the outer transaction
      // will rollback.
      this.sqlDb.setTransactionSuccessful();
    } finally {
      this.sqlDb.endTransaction();
      if (documentDeleted != null) {
        eventBus.post(documentDeleted);
      }
    }
  }
Exemplo n.º 28
0
 private GameController(final int width, final int height, final int turns) {
   _model = DrenchModel.Generator.createRandomModel(width, height, turns);
   _objective = width * height;
   _bus = new EventBus();
   _loader = new GameAILoader();
   _ai = _loader.defaultAI();
   _aiName = _loader.defaultAIName();
   _bus.register(this);
 }
Exemplo n.º 29
0
 @Override
 public Object postProcessBeforeInitialization(Object bean, String beanName)
     throws BeansException {
   if (shouldRegister(bean.getClass())) {
     logger.info("Registering {} with {}", bean, eventBus);
     eventBus.register(bean);
   }
   return bean;
 }
Exemplo n.º 30
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Object message = e.getMessage();

    if (message instanceof HttpRequest) {
      eventBus.post(message);
      httpRequestReceived((HttpRequest) message, e.getChannel());
    }
  }