/** * 监听链接关闭事件,清理失效的路由 * * @param event */ @Subscribe @AllowConcurrentEvents void on(ConnectionCloseEvent event) { Connection connection = event.connection; if (connection == null) return; SessionContext context = connection.getSessionContext(); String userId = context.userId; if (userId == null) return; String key = CacheKeys.getUserRouteKey(userId); String field = Integer.toString(context.getClientType()); ClientLocation location = cacheManager.hget(key, field, ClientLocation.class); if (location == null || location.isOffline()) return; String connId = connection.getId(); //2.检测下,是否是同一个链接, 如果客户端重连,老的路由会被新的链接覆盖 if (connId.equals(location.getConnId())) { cacheManager.hset(key, field, location.offline()); LOGGER.info("clean disconnected remote route, userId={}, route={}", userId, location); } else { LOGGER.info("clean disconnected remote route, not clean:userId={}, route={}", userId, location); } }
/** * 监听链接关闭事件,清理失效的路由 * * @param event */ @Subscribe @AllowConcurrentEvents void on(ConnectionCloseEvent event) { Connection connection = event.connection; if (connection == null) return; SessionContext context = connection.getSessionContext(); String userId = context.userId; if (userId == null) return; EventBus.post(new UserOfflineEvent(event.connection, userId)); int clientType = context.getClientType(); LocalRouter localRouter = routers.getOrDefault(userId, EMPTY).get(clientType); if (localRouter == null) return; String connId = connection.getId(); //2.检测下,是否是同一个链接, 如果客户端重连,老的路由会被新的链接覆盖 if (connId.equals(localRouter.getRouteValue().getId())) { //3.删除路由 routers.getOrDefault(userId, EMPTY).remove(clientType); LOGGER.info("clean disconnected local route, userId={}, route={}", userId, localRouter); } else { //如果不相等,则log一下 LOGGER.info("clean disconnected local route, not clean:userId={}, route={}", userId, localRouter); } }
@Subscribe @AllowConcurrentEvents public void on(final AssetEvent event) { // only make DB changes on the originating node, as orient will also replicate those for us if (event.isLocal() && member(event.getRepositoryName()) && event.getComponentId() == null) { final String path = event.getAsset().name(); final MavenPath mavenPath = mavenFacet.getMavenPathParser().parsePath(path); // group deletes path + path.hashes, but it should do only on content change in member if (!mavenPath.isHash()) { UnitOfWork.begin(getRepository().facet(StorageFacet.class).txSupplier()); try { evictCache(mavenPath); } catch (IOException e) { log.warn("Could not evict merged content from {} cache at {}", getRepository().getName(), mavenPath.getPath(), e); } finally { UnitOfWork.end(); } } } }
@AllowConcurrentEvents @Subscribe public void handle(final CapabilityEvent.BeforeUpdate event) { if (event.getReference().context().id().equals(id)) { if (propertyNames == null) { setSatisfied(false); } else { for (final String propertyName : propertyNames) { String oldValue = event.properties().get(propertyName); if (oldValue == null) { oldValue = ""; } String newValue = event.previousProperties().get(propertyName); if (newValue == null) { newValue = ""; } if (isSatisfied() && !oldValue.equals(newValue)) { setSatisfied(false); } } } } }
@Subscribe @AllowConcurrentEvents public void on(final RepositoryEvent event) { if (isRecording()) { Repository repository = event.getRepository(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(repository.getName()); Map<String, String> attributes = data.getAttributes(); attributes.put("name", repository.getName()); attributes.put("type", repository.getType().getValue()); attributes.put("format", repository.getFormat().getValue()); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final BlobStoreEvent event) { if (isRecording()) { BlobStore blobStore = event.getBlobStore(); BlobStoreConfiguration configuration = blobStore.getBlobStoreConfiguration(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(configuration.getName()); Map<String, String> attributes = data.getAttributes(); attributes.put("name", configuration.getName()); attributes.put("type", configuration.getType()); record(data); } }
@AllowConcurrentEvents @Subscribe public void handle(final CapabilityEvent.AfterUpdate event) { if (event.getReference().context().id().equals(capabilityIdentity)) { if (!sameRepositoryAs(repositoryBeforeLastUpdate)) { try { bindLock.writeLock().lock(); for (final Repository repository : repositoryManager.browse()) { handle(new RepositoryCreatedEvent(repository)); } } finally { bindLock.writeLock().unlock(); } } } }
@Subscribe @AllowConcurrentEvents public void on(final ComponentEvent event) { if (isRecording() && event.isLocal()) { Component component = event.getComponent(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(component.name()); Map<String, String> attributes = data.getAttributes(); attributes.put("repository.name", event.getRepositoryName()); attributes.put("format", component.format()); attributes.put("name", component.name()); attributes.put("group", component.group()); attributes.put("version", component.version()); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final AssetEvent event) { if (isRecording() && event.isLocal()) { Asset asset = event.getAsset(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(asset.name()); Map<String, String> attributes = data.getAttributes(); attributes.put("repository.name", event.getRepositoryName()); attributes.put("format", asset.format()); attributes.put("name", asset.name()); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final AnonymousConfigurationChangedEvent event) { if (isRecording()) { AnonymousConfiguration configuration = event.getConfiguration(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(CHANGED_TYPE); data.setContext(SYSTEM_CONTEXT); Map<String, String> attributes = data.getAttributes(); attributes.put("enabled", string(configuration.isEnabled())); attributes.put("userId", configuration.getUserId()); attributes.put("realm", configuration.getRealmName()); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final UserRoleMappingEvent event) { if (isRecording()) { AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(event.getUserId()); Map<String, String> attributes = data.getAttributes(); attributes.put("id", event.getUserId()); attributes.put("source", event.getUserSource()); attributes.put("roles", string(event.getRoles())); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final RealmConfigurationChangedEvent event) { if (isRecording()) { RealmConfiguration configuration = event.getConfiguration(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(CHANGED_TYPE); data.setContext(SYSTEM_CONTEXT); Map<String, String> attributes = data.getAttributes(); attributes.put("realms", string(configuration.getRealmNames())); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final RoleEvent event) { if (isRecording()) { Role role = event.getRole(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(role.getRoleId()); Map<String, String> attributes = data.getAttributes(); attributes.put("id", role.getRoleId()); attributes.put("name", role.getName()); attributes.put("source", role.getSource()); attributes.put("roles", string(role.getRoles())); attributes.put("privileges", string(role.getPrivileges())); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final UserEvent event) { if (isRecording()) { User user = event.getUser(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(user.getUserId()); Map<String, String> attributes = data.getAttributes(); attributes.put("id", user.getUserId()); attributes.put("name", user.getName()); attributes.put("email", user.getEmailAddress()); attributes.put("source", user.getSource()); attributes.put("status", user.getStatus().name()); attributes.put("roles", roles(user)); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final PrivilegeEvent event) { if (isRecording()) { Privilege privilege = event.getPrivilege(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(privilege.getId()); Map<String, String> attributes = data.getAttributes(); attributes.put("id", privilege.getId()); attributes.put("name", privilege.getName()); attributes.put("type", privilege.getType()); for (Entry<String,String> entry : privilege.getProperties().entrySet()) { attributes.put("property." + entry.getKey(), entry.getValue()); } record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final ScriptEvent event) { if (isRecording()) { Script script = event.getScript(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(script.getName()); Map<String, String> attributes = data.getAttributes(); attributes.put("name", script.getName()); attributes.put("type", script.getType()); record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final TaskEvent event) { if (isRecording()) { TaskInfo task = event.getTaskInfo(); TaskConfiguration configuration = task.getConfiguration(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(type(event.getClass())); data.setContext(configuration.getTypeName()); Map<String, String> attributes = data.getAttributes(); // TaskInfo.{id/name/message} are all delegates to configuration attributes.put("schedule", string(task.getSchedule())); attributes.put("currentState", string(task.getCurrentState())); attributes.put("lastRunState", string(task.getLastRunState())); // TODO: may want to use TaskDescriptor to provider better comprehension of the configuration // TODO: ... for now though, just include everything its simpler attributes.putAll(configuration.asMap()); record(data); } }
/** * Sends alert emails if necessary. */ @Subscribe @AllowConcurrentEvents public void on(final TaskEventStoppedFailed event) { final TaskInfo taskInfo = event.getTaskInfo(); if (taskInfo == null || taskInfo.getConfiguration().getAlertEmail() == null) { return; } try { sendEmail( taskInfo.getConfiguration().getAlertEmail(), taskInfo.getId(), taskInfo.getName(), event.getFailureCause() ); } catch (Exception e) { log.warn("Failed to send email", e); } }
@Subscribe @AllowConcurrentEvents public void on(final EmailConfigurationChangedEvent event) { if (isRecording()) { EmailConfiguration configuration = event.getConfiguration(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(CHANGED_TYPE); data.setContext(SYSTEM_CONTEXT); Map<String, String> attributes = data.getAttributes(); attributes.put("enabled", string(configuration.isEnabled())); attributes.put("host", configuration.getHost()); attributes.put("port", string(configuration.getPort())); attributes.put("username", configuration.getUsername()); attributes.put("fromAddress", configuration.getFromAddress()); attributes.put("subjectPrefix", configuration.getSubjectPrefix()); // TODO: various ssl/tls/trust-store shit record(data); } }
@Subscribe @AllowConcurrentEvents public void on(final LoggerLevelChangedEvent event) { if (isRecording()) { String logger = event.getLogger(); LoggerLevel level = event.getLevel(); AuditData data = new AuditData(); data.setDomain(DOMAIN); data.setType(CHANGED_TYPE); data.setContext(logger); Map<String,String> attributes = data.getAttributes(); attributes.put("logger", logger); attributes.put("level", string(level)); record(data); } }
@AllowConcurrentEvents @Subscribe public void handle(final ConditionEvent.Unsatisfied event) { if (event.getCondition() == nexusActiveCondition) { releaseValidity(); } else if (event.getCondition() == validityCondition) { reference.disable(); try { capabilityRegistry.remove(reference.context().id()); } catch (Exception e) { log.error("Failed to remove capability with id '{}'", reference.context().id(), e); } } }
@Subscribe @AllowConcurrentEvents public void onMoveSubmit(final IMoveSubmit moveSubmit) { // try { // Thread.sleep(1000); // } // catch (final InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } final IClient client = this.getServer().getClientByEndpoint(moveSubmit.getEndpoint()); final BlockplusGame blockplusGame = (BlockplusGame) this.getServer().getGame(client.getGame()); // System.out.println(); // System.out.println(blockplusGame.getOrdinal()); // System.out.println(); // System.out.println("is paused : " + blockplusGame.isPaused()); // System.out.println(); if (blockplusGame.isPaused()) { //System.out.println("PAUSED"); } else { final BlockplusGame newGame = (BlockplusGame) blockplusGame.play(moveSubmit); this.getServer().updateGame(newGame.getOrdinal(), newGame); newGame.update(); } }
@Subscribe @AllowConcurrentEvents public void onNotification(final INotification notificationInterface) { final IClient client = this.getServer().getClientByEndpoint(notificationInterface.getEndpoint()); final Integer game = client.getGame(); final BlockplusGame blockplusGame = (BlockplusGame) this.getServer().getGame(game); final Colors from = Colors.valueOf(notificationInterface.getFrom()); final Colors to = Colors.valueOf(notificationInterface.getTo()); final String message = notificationInterface.getMessage(); final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("message", message); jsonObject.addProperty("from", from.toString()); jsonObject.addProperty("to", to.toString()); final IClient toClient = blockplusGame.getPlayer(to); toClient.getEndpoint().emit("notification", jsonObject.toString()); }
@Subscribe @AllowConcurrentEvents public void handleEventConcurrent(CountDownLatch signal) { try { Date date = new Date(System.currentTimeMillis()); TestTable test = new TestTable(); test.setCount(signal.getCount()); test.setCreateDate(date); test.setId(UUID.randomUUID().toString()); test.setName("创建测试=" + UUID.randomUUID().toString()); TestTableWriter ttw = new TestTableWriter(); ttw.add(test); } catch (Exception ex) { Logger.getLogger(TestGenericSubscribe.class.getName()).log(Level.SEVERE, null, ex); } finally { signal.countDown(); } }
@Subscribe @AllowConcurrentEvents public void handleEventConcurrent(CountDownLatch signal) { try { Date date = new Date(System.currentTimeMillis()); TestTable test = new TestTable(); test.setCount(signal.getCount()); test.setCreateDate(date); test.setId(UUID.randomUUID().toString()); test.setName("创建测试=" + UUID.randomUUID().toString()); Transaction ts = new MySQLTransaction(); TestTableWriter ttw = new TestTableWriter(ts,"kamike"); ttw.add(test); ts.save(); } catch (Exception ex) { Logger.getLogger(TestGenericSubscribe.class.getName()).log(Level.SEVERE, null, ex); } finally { signal.countDown(); } }
/** * Populates the test summary map as soon as test filtering is complete. * This is the earliest at which the final set of targets to test is known. */ @Subscribe @AllowConcurrentEvents public void populateTests(TestFilteringCompleteEvent event) { // Add all target runs to the map, assuming 1:1 status artifact <-> result. synchronized (summaryLock) { for (ConfiguredTarget target : event.getTestTargets()) { Iterable<Artifact> statusArtifacts = target.getProvider(TestProvider.class).getTestParams().getTestStatusArtifacts(); Preconditions.checkState( remainingRuns.putAll(asKey(target), statusArtifacts), "target: %s, statusArtifacts: %s", target, statusArtifacts); // And create an empty summary suitable for incremental analysis. // Also has the nice side effect of mapping labels to RuleConfiguredTargets. TestSummary.Builder summary = TestSummary.newBuilder() .setTarget(target) .setStatus(BlazeTestStatus.NO_STATUS); TestSummary.Builder oldSummary = summaries.put(asKey(target), summary); Preconditions.checkState( oldSummary == null, "target: %s, summaries: %s %s", target, oldSummary, summary); } } }
@Subscribe @AllowConcurrentEvents public void handleBeforeModule(final InternalBeforeModuleEvent event) { TestModule module = event.getModule(); moduleArchiverProvider.get().startArchiving(); // if not explititly disabled, module are always reported Reported reported = module.getClass().getAnnotation(Reported.class); if (reported == null || reported.value()) { ReportContext reportContext = new ReportContext(); reportContext.setTestObjectName(module.getName()); reportContext.setTestObjectType(module.getClass()); reportContext.setStartMillis(System.currentTimeMillis()); reportContextStackProvider.get().push(reportContext); } }
@Subscribe @AllowConcurrentEvents public void handleAfterModule(final InternalAfterModuleEvent event) { TestModule module = event.getModule(); try { // if not explititly disabled, module are always reported Reported reported = module.getClass().getAnnotation(Reported.class); if (reported == null || reported.value()) { ReportContext reportContext = reportContextStackProvider.get().pop(); reportContext.setStopMillis(System.currentTimeMillis()); reportContext.setThrowable(event.getThrowable()); addReportResults(reportContext); } } finally { moduleArchiverProvider.get().finishArchiving(); } }
/** * Event handler method used by the {@link EventBus}. If configured for the given event's class, * a screenshot is taken and stored in folder {@code screenshots} in the current module's * archive directory. The screenshot images are named by the event class' simple name, prefixed * with a left-padded four-digit integer counter (format: {@code %04d_%s.png}). * * @param event * the event */ @Subscribe @AllowConcurrentEvents public void handleEvent(final AbstractBaseEvent event) { Class<? extends AbstractBaseEvent> clazz = event.getClass(); boolean errorCapture = captureScreenOnError(event); boolean eventConfigured = screenCaptureEvents.contains(clazz); if (eventConfigured || errorCapture) { String screenshotName = clazz.getSimpleName(); if (errorCapture) { screenshotName += "_error"; } captureAndArchiveScreen(screenshotName); } }
@AllowConcurrentEvents @Subscribe public void onCellIdChanged(CellChangedEvent event) { appStatisticsService.incStatisticStatistics(STATISTIC_NAME, "Events processed"); Track track = event.getTrack(); Float sog = track.getSpeedOverGround(); if (sog != null && sog >= 2.0) { Long cellId = (Long) track.getProperty(Track.CELL_ID); Integer shipType = track.getShipType(); Integer shipLength = track.getVesselLength(); Float cog = track.getCourseOverGround(); if (isInputValid(cellId, shipType, shipLength, cog)) { short shipTypeBucket = Categorizer.mapShipTypeToCategory(shipType); short shipSizeBucket = Categorizer.mapShipLengthToCategory(shipLength); short cogBucket = Categorizer.mapCourseOverGroundToCategory(cog); incrementStatisticStatistics(cellId, shipTypeBucket, shipSizeBucket, cogBucket); appStatisticsService.incStatisticStatistics(this.getClass().getSimpleName(), "Events processed ok"); } } }
@AllowConcurrentEvents @Subscribe public void onCellIdChanged(CellChangedEvent event) { appStatisticsService.incStatisticStatistics(STATISTIC_NAME, "Events processed"); Track track = event.getTrack(); Float sog = track.getSpeedOverGround(); if (sog != null) { Long cellId = (Long) track.getProperty(Track.CELL_ID); Integer shipType = track.getShipType(); Integer shipLength = track.getVesselLength(); if (isInputValid(cellId, shipType, shipLength, sog)) { short shipTypeBucket = Categorizer.mapShipTypeToCategory(shipType); short shipSizeBucket = Categorizer.mapShipLengthToCategory(shipLength); short sogBucket = Categorizer.mapSpeedOverGroundToCategory(sog); incrementStatisticStatistics(cellId, shipTypeBucket, shipSizeBucket, sogBucket); appStatisticsService.incStatisticStatistics(this.getClass().getSimpleName(), "Events processed ok"); } } }
/** * Percepts any {@link TestEvent test event} and registers it to the underlying queue. * * @param event * the percepted test event to register. */ @Subscribe @AllowConcurrentEvents public void receivedTestEvent(final TestEvent event) { synchronized (events) { events.put(event.getSessionId(), valueOf(event)); } if (null != latch) { latch.countDown(); } }
/** * Percepts a test session failure event, registers the session ID of the failed session. * * @param event * the failure event. */ @Subscribe @AllowConcurrentEvents public void sessionFailed(final SessionFailedEvent event) { LOGGER.info("Received test session failed event. " + (event.getComment().isPresent() ? event.getComment().get() : "")); failedSessionIds.add(event.getSessionId()); countDown(); }
/** * Percepts a test session completed event, registers the session ID of the completed session. * * @param event * the session completed event. */ @Subscribe @AllowConcurrentEvents public void sessionCompleted(final SessionFinishedEvent event) { LOGGER.info("Received test session finished event. Session ID: '" + event.getSessionId() + "'."); completedSessionIds.add(event.getSessionId()); countDown(); }
/** * Whenever a new test event from 'mangelhaft' on the Javascript side is being received by the HTTP server, this * method will be invoked. * <p> * <b>This is the only method in this class that may be invoked from a non-UI thread.</b> */ @Subscribe @AllowConcurrentEvents public void onTestEvent(TestEvent ev) { Display.getDefault().asyncExec(() -> { notifyTestEvent(ev); }); }
@Subscribe @AllowConcurrentEvents void on(ConnectionConnectEvent event) { Connection connection = event.connection; String hostAndPort = connection.getChannel().attr(attrKey).getAndSet(null); if (hostAndPort == null) { InetSocketAddress address = (InetSocketAddress) connection.getChannel().remoteAddress(); hostAndPort = getHostAndPort(address.getAddress().getHostAddress(), address.getPort()); } connections.computeIfAbsent(hostAndPort, key -> new ArrayList<>(gateway_client_num)).add(connection); logger.info("one gateway client connect success, hostAndPort={}, conn={}", hostAndPort, connection); }
@Subscribe @AllowConcurrentEvents void on(RouterChangeEvent event) { String userId = event.userId; Router<?> r = event.router; if (r.getRouteType().equals(Router.RouterType.LOCAL)) { sendKickUserMessage2Client(userId, (LocalRouter) r); } else { sendKickUserMessage2MQ(userId, (RemoteRouter) r); } }
@Subscribe @AllowConcurrentEvents public void listenUserEvent(UserEvent userEvent) { if (userEvent.getType().equals(UserEventType.REGISTER)) { LOG.info("add a new user,name:{},age:{}. total register user:{}.", userEvent.getName(), userEvent.getAge(), registerCounter.incrementAndGet()); } else if (userEvent.getType().equals(UserEventType.LOGIN)) { LOG.info("user:{} login,all user total login times:{}.", userEvent.getName(), loginCounter.incrementAndGet()); } else { throw new IllegalStateException("unknown user event type"); } }
@AllowConcurrentEvents @Subscribe public void handle(final CapabilityEvent event) { if (event.getReference().context().descriptor().type().equals(LegacyUrlCapabilityDescriptor.TYPE)) { toggleLegacyHttpBridgeModule(); } }
@Subscribe @AllowConcurrentEvents public void on(final EntityBatchEvent batchEvent) { // are we affected by this event? boolean deleteCatalog = false; for (final EntityEvent event : batchEvent.getEvents()) { if (event instanceof ComponentEvent) { final ComponentEvent componentEvent = (ComponentEvent) event; if (getRepository().getName().equals(componentEvent.getRepositoryName()) && MAVEN_ARCHETYPE_PACKAGING.equals( componentEvent.getComponent().formatAttributes().get(Attributes.P_PACKAGING, String.class))) { deleteCatalog = true; break; } } } if (deleteCatalog) { UnitOfWork.begin(getRepository().facet(StorageFacet.class).txSupplier()); try { TransactionalDeleteBlob.operation.throwing(IOException.class).call(() -> MavenFacetUtils.deleteWithHashes(mavenFacet, archetypeCatalogMavenPath) ); } catch (IOException e) { log.warn("Could not delete {}", archetypeCatalogMavenPath, e); } finally { UnitOfWork.end(); } } }