org.springframework.jmx.export.annotation.ManagedOperation Java Examples

The following examples show how to use org.springframework.jmx.export.annotation.ManagedOperation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RecoveryManager.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Runs all refresh actions.
 */
@ManagedOperation(description = "Runs all recovery actions - to be used after a unclean server shutdown (kill)")
public void recover() {
  if (!stopRequested) {
    publishUnpublishedAlarms(); //unpublished alarms are sent to LASER
  }
  if (!stopRequested) {
    refreshStateTags(); //updates the tags with the current status
  }
  if (!stopRequested) {
    refreshDataTags(); //gets latest values from DAQ cache
  }
  if (!stopRequested) {
    notifyAllTagCacheListeners(); //also refreshes rules but not alarms (done with supervision)
  }
  //IMPORTANT: MUST BE CALLED LAST AS UPDATES TO RULES OR TAGS MAY HAVE OVERWRITTEN CURRENT SUPERVISION STATUS IF CACHE LISTENER
  //TAKES ACTION ON STATUS CONFIRMATION (ALTHOUGH THIS IS NOT RECOMMENDED - SEE TimCacheListener INTERFACE FOR DETAILS)
  if (!stopRequested) {
    refreshSupervisionStatus(); //generates new events with the current status; includes alarm callbacks!;
  }
}
 
Example #2
Source File: CommandTagConfigurationManager.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@ManagedOperation(description = "Persists the current cache configurations to the DB (cache persistence). Ensures cache object runtime values & DB are synchronized.")
public void persistAllCacheConfigurationToDatabase() {
  try {
    List<Long> tagIdList = commandTagCache.getKeys();

    log.debug("Persisting " + tagIdList.size() + " configuration of cache object(s) to the database (CommandTag)");
    int counter = 0, overall = 0;
    for (Long id : tagIdList) {
      commandTagDAO.updateCommandTag(commandTagCache.getCopy(id));
      counter++;
      overall++;
      if (counter >= tagIdList.size() * 0.1) {
        counter = 0;
        log.debug("JMX update progress: " + (int) (((overall * 1.0) / tagIdList.size()) * 100) + "%");
      }
    }
  } catch (Exception e){
    log.warn("Error occurred whilst persisting all command tag configurations.", e);
  }
}
 
Example #3
Source File: RecoveryManager.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Notifies all Alarm cache listeners using the status confirmation call.
 * This will re-persist all the cache to the cache DB account (TIMPRO); re-publish
 * all alarm values to the C2MON clients; publish unpublished alarms to LASER (these
 * should normally be picked up by the publication-check thread in any case).
 *
 * <p>Notice that the alarm cache incorporates the current supervision status, unlike
 * the Tag caches, so it is not necessary to refresh the supervision status after this
 * call.
 */
@ManagedOperation(description = "Notifies all Alarm cache listeners (status confirmation).")
public void notifyAllAlarmCacheListeners() {
  log.info("Recovery task: notifying all alarm cache listeners (cache persistence to DB, re-publication to clients, publication to LASER if not already done)");
  for (Long key : alarmCache.getKeys()) {
    alarmCache.acquireWriteLockOnKey(key);
    try {
      Alarm alarm = alarmCache.getCopy(key);
      long eventTime = System.currentTimeMillis();
      alarmCache.notifyListenerStatusConfirmation(alarm, eventTime);
    } finally {
      alarmCache.releaseWriteLockOnKey(key);
    }
  }
  log.info("Recovery task: finished notifying all alarm cache listeners.");
}
 
Example #4
Source File: GroovyCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@ManagedOperation(description = "Enables Groovy shell for this instance for specified amount of time (ms)")
public synchronized void setEnabled(boolean enabled, long duration) {
    if (!enabled && !this.enabled || enabled && this.enabled) {
        log.warn("Groovy Shell already in this state!");
        return;
    }

    if (!enabled) {
        this.enabled = false;
        log.warn("Groovy Shell disabled!");
        return;
    }
    this.enabled = true;
    log.warn("Groovy Shell command enabled for {} ms!", duration);
    scheduler.schedule(() -> {
        if (this.enabled) {
            this.enabled = false;
            log.warn("Groovy Shell disabled by timeout", duration);
        }
    }, DateTime.now().plus(duration).toDate());
}
 
Example #5
Source File: BankMoneyTransferService.java    From Hands-On-High-Performance-with-Spring-5 with MIT License 6 votes vote down vote up
@ManagedOperation(description = "Amount transfer")
@ManagedOperationParameters({
		@ManagedOperationParameter(name = "sourceAccount", description = "Transfer from account"),
		@ManagedOperationParameter(name = "destinationAccount", description = "Transfer to account"),
		@ManagedOperationParameter(name = "transferAmount", description = "Amount to be transfer") })
public void transfer(String sourceAccount, String destinationAccount, int transferAmount) {
	if (transferAmount == 0) {
		throw new IllegalArgumentException("Invalid amount");
	}
	int sourceAcctBalance = accountMap.get(sourceAccount);
	int destinationAcctBalance = accountMap.get(destinationAccount);

	if ((sourceAcctBalance - transferAmount) < 0) {
		throw new IllegalArgumentException("Not enough balance.");
	}
	sourceAcctBalance = sourceAcctBalance - transferAmount;
	destinationAcctBalance = destinationAcctBalance + transferAmount;

	accountMap.put(sourceAccount, sourceAcctBalance);
	accountMap.put(destinationAccount, destinationAcctBalance);
}
 
Example #6
Source File: EurekaMgmtEndpoint.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "instance-status", method = RequestMethod.POST)
@ResponseBody
@ManagedOperation
public Object setStatus(@RequestBody String status) {
    if (!this.isEnabled()) {
        return new ResponseEntity<>(Collections.singletonMap("message", "This endpoint is disabled"),
            HttpStatus.NOT_FOUND);
    }
    Assert.notNull(status, "status may not by null");
    if (this.registration == null) {
        throw new RuntimeException("No registration found.");
    }
    this.serviceRegistry.setStatus(this.registration, status);
    LOGGER.info("ServiceDiscoveryMgmtEndpoint, set status for service id = {}, status = {}",
        registration.getServiceId(), status);
    return "success";
}
 
Example #7
Source File: EurekaMgmtEndpoint.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "dynamicsroute", method = RequestMethod.GET)
@ManagedOperation
public Object setDynamicsRoute(@RequestParam("serviceId") String serviceId,
    @RequestParam("routeIp") String routeIp) {
    if (!this.isEnabled()) {
        return new ResponseEntity<>(Collections.singletonMap("message", "This endpoint is disabled"),
            HttpStatus.NOT_FOUND);
    }
    Assert.notNull(serviceId, "serviceId may not by null");
    Assert.notNull(routeIp, "routeIp may not by null");
    if (this.registration == null) {
        throw new RuntimeException("No registration found.");
    }
    this.eurekaRuleCache.put(serviceId, routeIp);
    LOGGER.info("ServiceDiscoveryMgmtEndpoint, DynamicsRoute for service id = {}, routeIp = {}", serviceId,
        routeIp);
    return "success";
}
 
Example #8
Source File: EurekaMgmtEndpoint.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "deregister", method = RequestMethod.POST)
@ResponseBody
@ManagedOperation
public Object deregister() {
    if (!this.isEnabled()) {
        return new ResponseEntity<>(Collections.singletonMap("message", "This endpoint is disabled"),
            HttpStatus.NOT_FOUND);
    }
    if (this.registration == null) {
        throw new RuntimeException("No registration found.");
    }

    this.serviceRegistry.deregister(this.registration);
    LOGGER.info("ServiceDiscoveryMgmtEndpoint, deregister for service id  = {}", registration.getServiceId());
    return "success";
}
 
Example #9
Source File: TacoCounter.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@ManagedOperation
public long increment(long delta) {
  long before = counter.get();
  long after = counter.addAndGet(delta);
  if ((after / 100) > (before / 100)) {
    Notification notification = new Notification(
        "taco.count", this,
        before, after + "th taco created!");
    np.sendNotification(notification);
  }
  return after;
}
 
Example #10
Source File: CommandTagConfigurationManager.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ManagedOperation(description = "Persists the current cache configurations to the DB (cache persistence). Ensures cache object runtime values & DB are synchronized.")
public void persistAllCacheConfigurationToDatabaseParallel() {
  try {
    log.debug("Persisting " + commandTagCache.getKeys().size() + " configuration of cache object(s) to the database (CommandTag)");
    commandTagCache.getKeys().parallelStream().forEach((key) -> commandTagDAO.updateCommandTag(commandTagCache.getCopy(key)));
    log.debug("Persisting commandTags configuration done");

  }catch (Exception e){
    log.warn("Error occurred whilst persisting all command tag configurations.", e);
  }
}
 
Example #11
Source File: PersistenceManagerMBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a JPQL update statement.
 * @param queryString   JPQL update statement
 * @param softDeletion  soft deletion sign
 * @return              number of entity instances affected by update
 */
@ManagedOperation(description = "Execute a JPQL update statement")
@ManagedOperationParameters({
        @ManagedOperationParameter(name = "queryString", description = ""),
        @ManagedOperationParameter(name = "softDeletion", description = "")
})
String jpqlExecuteUpdate(String queryString, boolean softDeletion);
 
Example #12
Source File: ConfigStorageMBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
@ManagedOperation(description = "Invoke a getter method of configuration interface and print the result")
@ManagedOperationParameters({
        @ManagedOperationParameter(name = "classFQN", description = "Fully qualified name of a configuration interface"),
        @ManagedOperationParameter(name = "methodName", description = "Getter method name"),
        @ManagedOperationParameter(name = "userLogin", description = "User login that will be used for creating a user session")
})
String getConfigValue(String classFQN, String methodName, String userLogin);
 
Example #13
Source File: JmsProxyImpl.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ManagedOperation(description = "Get size of current internal listener queues")
public Map<String, Integer> getQueueSizes() {
  Map<String, Integer> returnMap = new HashMap<>();
  for (Map.Entry<String, MessageListenerWrapper> entry : topicToWrapper.entrySet()) {
    returnMap.put(entry.getKey(), entry.getValue().getQueueSize());
  }

  returnMap.put(supervisionTopic.toString(), supervisionListenerWrapper.getQueueSize());
  returnMap.put(alarmTopic.toString(), alarmListenerWrapper.getQueueSize());
  if (adminMessageTopic != null) {
    returnMap.put(adminMessageTopic.toString(), broadcastMessageListenerWrapper.getQueueSize());
  }
  returnMap.put(heartbeatTopic.toString(), heartbeatListenerWrapper.getQueueSize());
  return returnMap;
}
 
Example #14
Source File: TagConfigDocumentIndexer.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Re-index all tag config documents from the cache.
 */
@ManagedOperation(description = "Re-indexes all tag configs from the cache to Elasticsearch")
public void reindexAllTagConfigDocuments() {
  if (tagFacadeGateway == null) {
    throw new IllegalStateException("Tag Facade Gateway is null");
  }

  for (Long id : tagFacadeGateway.getKeys()) {
    Tag tag = tagFacadeGateway.getTag(id);
    converter.convert(tag, tagFacadeGateway.getAlarms(tag)).ifPresent(this::updateTagConfig);
  }
}
 
Example #15
Source File: RecoveryManager.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Refresh the supervision status.
 */
@ManagedOperation(description = "Refreshes all supervision status.")
public void refreshSupervisionStatus() {
  log.info("Recovery task: notifying all supervision listeners of current status.");
  supervisionFacade.refreshAllSupervisionStatus();
  log.info("Recovery task: finished notifying supervision status (notice all alarms are now re-evaluated on a separate thread"
  		+ " - this may take some time!)");
}
 
Example #16
Source File: SupervisionNotifierImpl.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * For management purposes.
 * @return the number of active threads for each listener
 */
@ManagedOperation(description="Get listener active threads.")
public List<Integer> getNumActiveThreads() {
  ArrayList<Integer> activeThreads = new ArrayList<Integer>();
  listenerLock.writeLock().lock();
  try {
    for (SupervisionListener listener : supervisionListeners) {
      activeThreads.add(executors.get(listener).getActiveCount());
    }
  } finally {
    listenerLock.writeLock().unlock();
  }
  return activeThreads;
}
 
Example #17
Source File: Calculator.java    From Hands-On-High-Performance-with-Spring-5 with MIT License 5 votes vote down vote up
@ManagedOperation(description = "Calculate two numbers")
@ManagedOperationParameters({
		@ManagedOperationParameter(name = "x",
				description = "The first number"),
		@ManagedOperationParameter(name = "y",
				description = "The second number") })
public void calculate(int x, int y) {
	lastCalculation = x + y;
}
 
Example #18
Source File: DataGenerator.java    From the-app with Apache License 2.0 5 votes vote down vote up
@ManagedOperation
public void createOrdersMoreOrders(int orders) throws IOException {
    List<User> users = userRepository.findAll();
    List<Product> products = productRepository.findAll();
    List<Address> addresses = addressCsvReader.parseCsv();

    for (int i = 0; i < orders; i++) {
        saveOrder(users, products, addresses);
    }
}
 
Example #19
Source File: EurekaMgmtEndpoint.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path = "shutdown", method = RequestMethod.POST)
@ResponseBody
@ManagedOperation
public Object offline(@RequestParam(value = "shutdown", required = false, defaultValue = "true") boolean shutdown) {
    if (!this.isEnabled()) {
        return new ResponseEntity<>(Collections.singletonMap("message", "This endpoint is disabled"),
            HttpStatus.NOT_FOUND);
    }
    this.serviceRegistry.close();
    LOGGER.info("ServiceDiscoveryMgmtEndpoint, finish close");
    if (shutdown) {
        if (this.context == null) {
            throw new RuntimeException("Success close service registry but no context to shutdown.");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500L);
                } catch (InterruptedException ex) {

                }
                LOGGER.info("ServiceDiscoveryMgmtEndpoint, start shutdown app, bye...");
                EurekaMgmtEndpoint.this.context.close();
            }
        }).start();
    }
    return "success";
}
 
Example #20
Source File: DataGenerator.java    From the-app with Apache License 2.0 5 votes vote down vote up
@ManagedOperation
@PostConstruct
@Scheduled(fixedRate = 5000)
public void initializeDatabase() throws IOException {
    cleanCollections();
    createSupplierList();

    if (productRepository.findAll().isEmpty()) {
        logger.info("Database is empty: populating it");
        createProducts();
        createUsers();
        createOrders();
    }
}
 
Example #21
Source File: AbstractCache.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * For management purposes.
 * @return the number of active threads for multi-threaded listeners
 */
@ManagedOperation(description="Get listener active thread number.")
public List<Integer> getActiveThreadNumber() {
  ArrayList<Integer> threadPoolSizes = new ArrayList<Integer>();
  for (C2monCacheListener listener : cacheListeners) {
    if (listener instanceof MultiThreadedCacheListener) {
      threadPoolSizes.add(((MultiThreadedCacheListener) listener).getActiveThreadPoolNumber());
    }
  }
  return threadPoolSizes;
}
 
Example #22
Source File: RecoveryManager.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Refresh all state tags with new timestamps.
 */
@ManagedOperation(description = "Refreshes all state tags (new timestamp).")
public void refreshStateTags() {
  log.info("Recovery task: refreshing state tags.");
  supervisionFacade.refreshStateTags();
  log.info("Recovery task: finished refreshing state tags.");
}
 
Example #23
Source File: TacoCounter.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@ManagedOperation
public long increment(long delta) {
  long before = counter.get();
  long after = counter.addAndGet(delta);
  if ((after / 100) > (before / 100)) {
    Notification notification = new Notification(
        "taco.count", this,
        before, after + "th taco created!");
    np.sendNotification(notification);
  }
  return after;
}
 
Example #24
Source File: CallMonitoringAspect.java    From DevOps-for-Web-Development with MIT License 4 votes vote down vote up
@ManagedOperation
public void reset() {
    this.callCount = 0;
    this.accumulatedCallTime = 0;
}
 
Example #25
Source File: BruteForceProtectionMBean.java    From cuba with Apache License 2.0 4 votes vote down vote up
@ManagedOperation(description = "Unlocks the blocked user")
@ManagedOperationParameters(
        {@ManagedOperationParameter(name = "login", description = "User login"),
        @ManagedOperationParameter(name = "ipAddress", description = "User IP-address")})
void unlockUser(String login, String ipAddress);
 
Example #26
Source File: ClusterManagerMBean.java    From cuba with Apache License 2.0 4 votes vote down vote up
@ManagedOperation(description = "Get sent messages count for specified class")
long getSentMessages(String className);
 
Example #27
Source File: FeatureTooglesBean.java    From the-app with Apache License 2.0 4 votes vote down vote up
@ManagedOperation
public void toogleHighlightingFeature() {
    highlightingFeatureEnabled = !highlightingFeatureEnabled;
}
 
Example #28
Source File: FeatureTooglesBean.java    From the-app with Apache License 2.0 4 votes vote down vote up
@ManagedOperation
public void toogleTopSellerFeature() {
    topSellerFeatureEnabled = !topSellerFeatureEnabled;
}
 
Example #29
Source File: RepublisherImpl.java    From c2mon with GNU Lesser General Public License v3.0 4 votes vote down vote up
@ManagedOperation(description = "Returns the current number of events awaiting re-publication (should be 0 in normal operation)")
@Override
public int getSizeUnpublishedList() {
  return toBePublished.size();
}
 
Example #30
Source File: CallMonitoringAspect.java    From DevOps-for-Web-Development with MIT License 4 votes vote down vote up
@ManagedOperation
public void reset() {
    this.callCount = 0;
    this.accumulatedCallTime = 0;
}