All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.daemon.SpringApplicationAdminClient Maven / Gradle / Ivy

package org.springframework.daemon;

import java.io.IOException;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.springframework.jmx.JmxException;

class SpringApplicationAdminClient {
  static final String DEFAULT_OBJECT_NAME = "org.springframework.boot:type=Admin,name=SpringApplication";
  private final MBeanServerConnection connection;
  private final ObjectName objectName;

  SpringApplicationAdminClient(MBeanServerConnection connection, String jmxName) {
    this.connection = connection;
    this.objectName = toObjectName(jmxName);
  }

  public boolean isReady() {
    try {
      Object attribute = this.connection.getAttribute(this.objectName, "Ready");
      if (attribute instanceof Boolean) {
        return (Boolean) attribute;
      }
      return false;
    }
    catch (InstanceNotFoundException ex) {
      return false; // Instance not available yet
    }
    catch (AttributeNotFoundException ex) {
      throw new IllegalStateException("Unexpected: attribute 'Ready' not available", ex);
    }
    catch (ReflectionException ex) {
      throw new JmxException("Failed to retrieve Ready attribute", ex.getCause());
    }
    catch (MBeanException ex) {
      throw new JmxException(ex.getMessage(), ex);
    }
    catch (IOException ex) {
      throw new JmxException(ex.getMessage(), ex);
    }
  }

  public void stop() throws IOException, InstanceNotFoundException {
    try {
      this.connection.invoke(this.objectName, "shutdown", null, null);
    }
    catch (ReflectionException ex) {
      throw new JmxException("Shutdown failed", ex.getCause());
    }
    catch (MBeanException ex) {
      throw new JmxException("Could not invoke shutdown operation", ex);
    }
  }

  private ObjectName toObjectName(String name) {
    try {
      return new ObjectName(name);
    }
    catch (MalformedObjectNameException ex) {
      throw new IllegalArgumentException("Invalid jmx name '" + name + "'");
    }
  }

  public static JMXConnector connect(int port) throws IOException {
    String url = "service:jmx:rmi:///jndi/rmi://127.0.0.1:" + port + "/jmxrmi";
    JMXServiceURL serviceUrl = new JMXServiceURL(url);
    return JMXConnectorFactory.connect(serviceUrl, null);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy