Java Code Examples for javax.management.MBeanServerInvocationHandler#newProxyInstance()

The following examples show how to use javax.management.MBeanServerInvocationHandler#newProxyInstance() . 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: BasicJMXWriterReaderTest.java    From kieker with Apache License 2.0 6 votes vote down vote up
private void checkControllerStateAfterRecordsPassedToController(final IMonitoringController monitoringController)
		throws Exception {
	// Test the JMX Controller
	final JMXServiceURL serviceURL = new JMXServiceURL(
			"service:jmx:rmi:///jndi/rmi://localhost:" + BasicJMXWriterReaderTest.PORT + "/jmxrmi");
	final ObjectName controllerObjectName = new ObjectName(BasicJMXWriterReaderTest.DOMAIN, "type",
			BasicJMXWriterReaderTest.CONTROLLER);

	final JMXConnector jmx = JMXConnectorFactory.connect(serviceURL);
	final MBeanServerConnection mbServer = jmx.getMBeanServerConnection();

	final Object tmpObj = MBeanServerInvocationHandler.newProxyInstance(mbServer, controllerObjectName,
			IMonitoringController.class, false);
	final IMonitoringController ctrlJMX = (IMonitoringController) tmpObj;

	Assert.assertTrue(monitoringController.isMonitoringEnabled());
	Assert.assertTrue(ctrlJMX.isMonitoringEnabled());

	Assert.assertTrue(ctrlJMX.disableMonitoring());

	Assert.assertFalse(monitoringController.isMonitoringEnabled());
	Assert.assertFalse(ctrlJMX.isMonitoringEnabled());

	jmx.close();
}
 
Example 2
Source File: GridAbstractTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Return JMX bean.
 *
 * @param igniteInstanceName Ignite instance name.
 * @param grp Name of the group.
 * @param name Name of the bean.
 * @param clazz Class of the mbean.
 * @return MX bean.
 * @throws Exception If failed.
 */
public static <T> T getMxBean(String igniteInstanceName, String grp, String name, Class<T> clazz) {
    ObjectName mbeanName = null;

    try {
        mbeanName = U.makeMBeanName(igniteInstanceName, grp, name);
    }
    catch (MalformedObjectNameException e) {
        fail("Failed to register MBean.");
    }

    MBeanServer mbeanSrv = ManagementFactory.getPlatformMBeanServer();

    if (!mbeanSrv.isRegistered(mbeanName))
        throw new IgniteException("MBean not registered.");

    return MBeanServerInvocationHandler.newProxyInstance(mbeanSrv, mbeanName, clazz, false);
}
 
Example 3
Source File: SecurityJMXTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testBrowseExpiredMessages() throws Exception {
   JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi");
   JMXConnector connector = JMXConnectorFactory.connect(url, null);
   connector.connect();
   MBeanServerConnection connection = connector.getMBeanServerConnection();
   ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=TEST.Q");
   QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true);
   HashMap<String, String> headers = new HashMap<>();
   headers.put("timeToLive", Long.toString(2000));
   headers.put("JMSDeliveryMode", Integer.toString(DeliveryMode.PERSISTENT));
   queueMbean.sendTextMessage(headers, "test", "system", "manager");
   // allow message to expire on the queue
   TimeUnit.SECONDS.sleep(4);

   Connection c = new ActiveMQConnectionFactory("vm://localhost").createConnection("system", "manager");
   c.start();

   // browser consumer will force expiration check on addConsumer
   QueueBrowser browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("TEST.Q"));
   assertTrue("no message in the q", !browser.getEnumeration().hasMoreElements());

   // verify dlq got the message, no security exception as brokers context is now used
   browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("ActiveMQ.DLQ"));
   assertTrue("one message in the dlq", browser.getEnumeration().hasMoreElements());
}
 
Example 4
Source File: BasicJMXWriterReaderTest.java    From kieker with Apache License 2.0 6 votes vote down vote up
private void checkControllerStateBeforeRecordsPassedToController(final IMonitoringController monitoringController)
		throws Exception {
	// Test the JMX Controller
	final JMXServiceURL serviceURL = new JMXServiceURL(
			"service:jmx:rmi:///jndi/rmi://localhost:" + BasicJMXWriterReaderTest.PORT + "/jmxrmi");
	final ObjectName controllerObjectName = new ObjectName(BasicJMXWriterReaderTest.DOMAIN, "type",
			BasicJMXWriterReaderTest.CONTROLLER);

	final JMXConnector jmx = JMXConnectorFactory.connect(serviceURL);
	final MBeanServerConnection mbServer = jmx.getMBeanServerConnection();

	final Object tmpObj = MBeanServerInvocationHandler.newProxyInstance(mbServer, controllerObjectName,
			IMonitoringController.class, false);
	final IMonitoringController ctrlJMX = (IMonitoringController) tmpObj;

	Assert.assertTrue(monitoringController.isMonitoringEnabled());
	Assert.assertTrue(ctrlJMX.isMonitoringEnabled());

	jmx.close();
}
 
Example 5
Source File: JBossWorkManagerUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Obtain the default JBoss JCA WorkManager through a JMX lookup
 * for the JBossWorkManagerMBean.
 * @param mbeanName the JMX object name to use
 * @see org.jboss.resource.work.JBossWorkManagerMBean
 */
public static WorkManager getWorkManager(String mbeanName) {
	Assert.hasLength(mbeanName, "JBossWorkManagerMBean name must not be empty");
	try {
		Class<?> mbeanClass = JBossWorkManagerUtils.class.getClassLoader().loadClass(JBOSS_WORK_MANAGER_MBEAN_CLASS_NAME);
		InitialContext jndiContext = new InitialContext();
		MBeanServerConnection mconn = (MBeanServerConnection) jndiContext.lookup(MBEAN_SERVER_CONNECTION_JNDI_NAME);
		ObjectName objectName = ObjectName.getInstance(mbeanName);
		Object workManagerMBean = MBeanServerInvocationHandler.newProxyInstance(mconn, objectName, mbeanClass, false);
		Method getInstanceMethod = workManagerMBean.getClass().getMethod("getInstance");
		return (WorkManager) getInstanceMethod.invoke(workManagerMBean);
	}
	catch (Exception ex) {
		throw new IllegalStateException(
				"Could not initialize JBossWorkManagerTaskExecutor because JBoss API is not available", ex);
	}
}
 
Example 6
Source File: ManagementContextXBeanConfigTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void assertAuthentication(JMXConnector connector) throws Exception {
   connector.connect();
   MBeanServerConnection connection = connector.getMBeanServerConnection();
   ObjectName name = new ObjectName("test.domain:type=Broker,brokerName=localhost");
   BrokerViewMBean mbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, BrokerViewMBean.class, true);
   LOG.info("Broker " + mbean.getBrokerId() + " - " + mbean.getBrokerName());
}
 
Example 7
Source File: Client.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
   // This JMXServiceURL works only if the connector server is in-VM with
   // the connector. If this is not the case, set the correct host name.
   JMXServiceURL address = new JMXServiceURL("soap", null, 8080, "/jmxconnector");

   // Connect a JSR 160 JMXConnector to the server side
   JMXConnector connector = JMXConnectorFactory.connect(address);

   // Retrieve an MBeanServerConnection that represent the MBeanServer
   // the remote connector server is bound to
   MBeanServerConnection connection = connector.getMBeanServerConnection();

   // Call the server side as if it is a local MBeanServer
   ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
   Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true);
   MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy;

   System.out.println(delegate.getImplementationVendor() + " is cool !");

   // Register an MBean, and get notifications via the SOAP protocol
   connection.addNotificationListener(delegateName, new NotificationListener()
   {
      public void handleNotification(Notification notification, Object handback)
      {
         System.out.println("Got the following notification: " + notification);
      }
   }, null, null);

   ObjectName timerName = ObjectName.getInstance("services:type=Timer");
   connection.createMBean(Timer.class.getName(), timerName, null);

   // Unregistering the MBean to get another notification
   connection.unregisterMBean(timerName);

   // Allow the unregistration notification to arrive before killing this JVM
   Thread.sleep(1000);

   connector.close();
}
 
Example 8
Source File: Client.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
   // The JMXConnectorServer protocol, in this case is IIOP
   String serverProtocol = "iiop";

   // The RMI server's host: this is actually ignored by JSR 160
   // since this information is stored in the RMI stub.
   String serverHost = "host";

   // The host and port where the COSNaming service runs and the path under which the stub is registered.
   String namingHost = "localhost";
   int namingPort = 1199;
   String jndiPath = "/jmxconnector";

   // The address of the connector server
   JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + "/jndi/iiop://" + namingHost + ":" + namingPort + jndiPath);

   // Connect a JSR 160 JMXConnector to the server side
   JMXConnector connector = JMXConnectorFactory.connect(url);

   // Retrieve an MBeanServerConnection that represent the MBeanServer the remote
   // connector server is bound to
   MBeanServerConnection connection = connector.getMBeanServerConnection();

   // Call the server side as if it is a local MBeanServer
   ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
   Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true);
   MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy;

   // The magic of JDK 1.3 dynamic proxy and JSR 160:
   // delegate.getImplementationVendor() is actually a remote JMX call,
   // but it looks like a local, old-style, java call.
   System.out.println(delegate.getImplementationVendor() + " is cool !");
}
 
Example 9
Source File: Client.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
   // The JMXConnectorServer protocol, in this case is RMI.
   String serverProtocol = "rmi";

   // The RMI server's host: this is actually ignored by JSR 160
   // since this information is stored in the RMI stub.
   String serverHost = "host";

   // The host, port and path where the rmiregistry runs.
   String namingHost = "localhost";
   int namingPort = 1099;
   String jndiPath = "/jmxconnector";

   // The address of the connector server
   JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + "/jndi/rmi://" + namingHost + ":" + namingPort + jndiPath);

   // Connect a JSR 160 JMXConnector to the server side
   JMXConnector connector = JMXConnectorFactory.connect(url);

   // Retrieve an MBeanServerConnection that represent the MBeanServer the remote
   // connector server is bound to
   MBeanServerConnection connection = connector.getMBeanServerConnection();

   // Call the server side as if it is a local MBeanServer
   ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
   Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true);
   MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy;

   // The magic of JDK 1.3 dynamic proxy and JSR 160:
   // delegate.getImplementationVendor() is actually a remote JMX call,
   // but it looks like a local, old-style, java call.
   System.out.println(delegate.getImplementationVendor() + " is cool !");
}
 
Example 10
Source File: CounterMonitorThresholdTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void runTest(int offset,
                           int counter[],
                           int derivedGauge[],
                           int threshold[]) throws Exception {
    // Retrieve the platform MBean server
    //
    System.out.println("\nRetrieve the platform MBean server");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = mbs.getDefaultDomain();

    // Create and register TestMBean
    //
    ObjectName name =
        new ObjectName(domain +
                       ":type=" + Test.class.getName() +
                       ",offset=" + offset);
    mbs.createMBean(Test.class.getName(), name);
    TestMBean mbean = (TestMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, name, TestMBean.class, false);

    // Create and register CounterMonitorMBean
    //
    ObjectName cmn =
        new ObjectName(domain +
                       ":type=" + CounterMonitor.class.getName() +
                       ",offset=" + offset);
    CounterMonitor m = new CounterMonitor();
    mbs.registerMBean(m, cmn);
    CounterMonitorMBean cm = (CounterMonitorMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, cmn, CounterMonitorMBean.class, true);
    ((NotificationEmitter) cm).addNotificationListener(
        new Listener(), null, null);
    cm.addObservedObject(name);
    cm.setObservedAttribute("Counter");
    cm.setGranularityPeriod(100);
    cm.setInitThreshold(1);
    cm.setOffset(offset);
    cm.setModulus(5);
    cm.setNotify(true);

    // Start the monitor
    //
    System.out.println("\nStart monitoring...");
    cm.start();

    // Play with counter
    //
    for (int i = 0; i < counter.length; i++) {
        mbean.setCounter(counter[i]);
        System.out.println("\nCounter = " + mbean.getCounter());
        Integer derivedGaugeValue;
        // either pass or test timeout (killed by test harness)
        // see 8025207
        do {
            Thread.sleep(150);
            derivedGaugeValue = (Integer) cm.getDerivedGauge(name);
        } while (derivedGaugeValue.intValue() != derivedGauge[i]);

        Number thresholdValue = cm.getThreshold(name);
        System.out.println("Threshold = " + thresholdValue);
        if (thresholdValue.intValue() != threshold[i]) {
            System.out.println("Wrong threshold! Current value = " +
                thresholdValue + " Expected value = " + threshold[i]);
            System.out.println("\nStop monitoring...");
            cm.stop();
            throw new IllegalArgumentException("wrong threshold");
        }
    }

    // Stop the monitor
    //
    System.out.println("\nStop monitoring...");
    cm.stop();
}
 
Example 11
Source File: ManagementControlHelper.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public static Object createProxy(final ObjectName objectName,
                                  final Class mbeanInterface,
                                  final MBeanServer mbeanServer) {
   return MBeanServerInvocationHandler.newProxyInstance(mbeanServer, objectName, mbeanInterface, false);
}
 
Example 12
Source File: JmxServerControlTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testListConsumers() throws Exception {
   // Without this, the RMI server would bind to the default interface IP (the user's local IP mostly)
   System.setProperty("java.rmi.server.hostname", JMX_SERVER_HOSTNAME);

   // I don't specify both ports here manually on purpose. See actual RMI registry connection port extraction below.
   String urlString = "service:jmx:rmi:///jndi/rmi://" + JMX_SERVER_HOSTNAME + ":" + JMX_SERVER_PORT + "/jmxrmi";

   JMXServiceURL url = new JMXServiceURL(urlString);
   JMXConnector jmxConnector = null;

   try {
      jmxConnector = JMXConnectorFactory.connect(url);
      System.out.println("Successfully connected to: " + urlString);
   } catch (Exception e) {
      jmxConnector = null;
      e.printStackTrace();
      Assert.fail(e.getMessage());
   }

   try {
      MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
      String brokerName = "0.0.0.0";  // configured e.g. in broker.xml <broker-name> element
      ObjectNameBuilder objectNameBuilder = ObjectNameBuilder.create(ActiveMQDefaultConfiguration.getDefaultJmxDomain(), brokerName, true);
      ActiveMQServerControl activeMQServerControl = MBeanServerInvocationHandler.newProxyInstance(mBeanServerConnection, objectNameBuilder.getActiveMQServerObjectName(), ActiveMQServerControl.class, false);

      String addressName = "test_list_consumers_address";
      String queueName = "test_list_consumers_queue";
      activeMQServerControl.createAddress(addressName, RoutingType.ANYCAST.name());
      activeMQServerControl.createQueue(new QueueConfiguration(queueName).setAddress(addressName).setRoutingType(RoutingType.ANYCAST).toJSON());
      String uri = "tcp://localhost:61616";
      try (ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory(uri, null)) {
         MessageConsumer consumer = cf.createConnection().createSession(true, Session.SESSION_TRANSACTED).createConsumer(new ActiveMQQueue(queueName));

         try {
            String options = JsonUtil.toJsonObject(ImmutableMap.of("field","queue", "operation", "EQUALS", "value", queueName)).toString();
            String consumersAsJsonString = activeMQServerControl.listConsumers(options, 1, 10);

            JsonObject consumersAsJsonObject = JsonUtil.readJsonObject(consumersAsJsonString);
            JsonArray array = (JsonArray) consumersAsJsonObject.get("data");

            Assert.assertEquals("number of consumers returned from query", 1, array.size());
            JsonObject jsonConsumer = array.getJsonObject(0);
            Assert.assertEquals("queue name in consumer", queueName, jsonConsumer.getString("queue"));
            Assert.assertEquals("address name in consumer", addressName, jsonConsumer.getString("address"));
         } finally {
            consumer.close();
         }
      }
   } finally {
      jmxConnector.close();
   }
}
 
Example 13
Source File: CounterMonitorThresholdTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void runTest(int offset,
                           int counter[],
                           int derivedGauge[],
                           int threshold[]) throws Exception {
    // Retrieve the platform MBean server
    //
    System.out.println("\nRetrieve the platform MBean server");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = mbs.getDefaultDomain();

    // Create and register TestMBean
    //
    ObjectName name =
        new ObjectName(domain +
                       ":type=" + Test.class.getName() +
                       ",offset=" + offset);
    mbs.createMBean(Test.class.getName(), name);
    TestMBean mbean = (TestMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, name, TestMBean.class, false);

    // Create and register CounterMonitorMBean
    //
    ObjectName cmn =
        new ObjectName(domain +
                       ":type=" + CounterMonitor.class.getName() +
                       ",offset=" + offset);
    CounterMonitor m = new CounterMonitor();
    mbs.registerMBean(m, cmn);
    CounterMonitorMBean cm = (CounterMonitorMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, cmn, CounterMonitorMBean.class, true);
    ((NotificationEmitter) cm).addNotificationListener(
        new Listener(), null, null);
    cm.addObservedObject(name);
    cm.setObservedAttribute("Counter");
    cm.setGranularityPeriod(100);
    cm.setInitThreshold(1);
    cm.setOffset(offset);
    cm.setModulus(5);
    cm.setNotify(true);

    // Start the monitor
    //
    System.out.println("\nStart monitoring...");
    cm.start();

    // Play with counter
    //
    for (int i = 0; i < counter.length; i++) {
        mbean.setCounter(counter[i]);
        System.out.println("\nCounter = " + mbean.getCounter());
        Integer derivedGaugeValue;
        // either pass or test timeout (killed by test harness)
        // see 8025207
        do {
            Thread.sleep(150);
            derivedGaugeValue = (Integer) cm.getDerivedGauge(name);
        } while (derivedGaugeValue.intValue() != derivedGauge[i]);

        Number thresholdValue = cm.getThreshold(name);
        System.out.println("Threshold = " + thresholdValue);
        if (thresholdValue.intValue() != threshold[i]) {
            System.out.println("Wrong threshold! Current value = " +
                thresholdValue + " Expected value = " + threshold[i]);
            System.out.println("\nStop monitoring...");
            cm.stop();
            throw new IllegalArgumentException("wrong threshold");
        }
    }

    // Stop the monitor
    //
    System.out.println("\nStop monitoring...");
    cm.stop();
}
 
Example 14
Source File: RunForecastErrorsAnalysisMpiTool.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {

    OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault();

    String host = line.getOptionValue(OnlineWorkflowCommand.HOST);
    String port = line.getOptionValue(OnlineWorkflowCommand.PORT);
    String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS);
    if (host != null) {
        startconfig.setJmxHost(host);
    }
    if (port != null) {
        startconfig.setJmxPort(Integer.valueOf(port));
    }
    if (threads != null) {
        startconfig.setThreads(Integer.valueOf(threads));
    }

    String analysisId = line.getOptionValue("analysis");
    DateTime baseCaseDate = line.hasOption("base-case-date")
            ? DateTime.parse(line.getOptionValue("base-case-date"))
            : getDefaultParameters().getBaseCaseDate();
    Interval histoInterval = line.hasOption("history-interval")
            ? Interval.parse(line.getOptionValue("history-interval"))
            : getDefaultParameters().getHistoInterval();
    double ir = line.hasOption("ir")
            ? Double.parseDouble(line.getOptionValue("ir"))
            : getDefaultParameters().getIr();
    int flagPQ = line.hasOption("flagPQ")
            ? Integer.parseInt(line.getOptionValue("flagPQ"))
            : getDefaultParameters().getFlagPQ();
    int method = line.hasOption("method")
            ? Integer.parseInt(line.getOptionValue("method"))
            : getDefaultParameters().getMethod();
    Integer nClusters = line.hasOption("nClusters")
            ? Integer.parseInt(line.getOptionValue("nClusters"))
            : getDefaultParameters().getnClusters();
    double percentileHistorical = line.hasOption("percentileHistorical")
            ? Double.parseDouble(line.getOptionValue("percentileHistorical"))
            : getDefaultParameters().getPercentileHistorical();
    Integer modalityGaussian = line.hasOption("modalityGaussian")
            ? Integer.parseInt(line.getOptionValue("modalityGaussian"))
            : getDefaultParameters().getModalityGaussian();
    Integer outliers = line.hasOption("outliers")
            ? Integer.parseInt(line.getOptionValue("outliers"))
            : getDefaultParameters().getOutliers();
    Integer conditionalSampling = line.hasOption("conditionalSampling")
            ? Integer.parseInt(line.getOptionValue("conditionalSampling"))
            : getDefaultParameters().getConditionalSampling();
    Integer nSamples = line.hasOption("nSamples")
            ? Integer.parseInt(line.getOptionValue("nSamples"))
            : getDefaultParameters().getnSamples();
    Set<Country> countries = line.hasOption("countries")
            ? Arrays.stream(line.getOptionValue("countries").split(",")).map(Country::valueOf).collect(Collectors.toSet())
            : getDefaultParameters().getCountries();
    CaseType caseType = line.hasOption("case-type")
            ? CaseType.valueOf(line.getOptionValue("case-type"))
            : getDefaultParameters().getCaseType();
    boolean allInjections = line.hasOption("all-injections")
            ? true
            : getDefaultParameters().isAllInjections();

    ForecastErrorsAnalysisParameters parameters = new ForecastErrorsAnalysisParameters(baseCaseDate, histoInterval, analysisId, ir, flagPQ, method, nClusters,
                                                                                       percentileHistorical, modalityGaussian, outliers, conditionalSampling,
                                                                                       nSamples, countries, caseType, allInjections);


    String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":" + startconfig.getJmxPort() + "/jmxrmi";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    Map<String, String> jmxEnv = new HashMap<>();
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();

    ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
    LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name, LocalOnlineApplicationMBean.class, false);
    String timeHorizonS = "";
    if (line.hasOption("time-horizon")) {
        timeHorizonS = line.getOptionValue("time-horizon");
    }
    application.runFeaAnalysis(startconfig, parameters, timeHorizonS);

}
 
Example 15
Source File: SSLHttpAdaptor.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Starts the http server
 */
public void start() throws JMException
{
   // creates new server
   MBeanServer server = MBeanServerFactory.createMBeanServer("test");
   ObjectName serverName = new ObjectName("Http:name=HttpAdaptor");
   server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", serverName, null);
   // set attributes
   if (port > 0)
   {
      server.setAttribute(serverName, new Attribute("Port", new Integer(port)));
   }
   else
   {
      System.out.println("Incorrect port value " + port);
   }
   if (host != null)
   {
      server.setAttribute(serverName, new Attribute("Host", host));
   }
   else
   {
      System.out.println("Incorrect null hostname");
   }
   // set the XSLTProcessor. If you want to use pure XML comment this out
   ObjectName processorName = new ObjectName("Http:name=XSLTProcessor");
   server.createMBean("mx4j.tools.adaptor.http.XSLTProcessor", processorName, null);
   if (path != null)
   {
      server.setAttribute(processorName, new Attribute("File", path));
   }
   server.setAttribute(processorName, new Attribute("UseCache", new Boolean(false)));
   if (pathInJar != null)
   {
      server.setAttribute(processorName, new Attribute("PathInJar", pathInJar));
   }
   server.setAttribute(serverName, new Attribute("ProcessorName", processorName));

   // add a couple of MBeans
   TestClass test1 = new TestClass("t1");
   TestClass test2 = new TestClass("t2");
   server.registerMBean(test1, new ObjectName("Test:name=test1"));
   server.registerMBean(test2, new ObjectName("Test:name=test2"));

   // add user names
   //server.invoke(serverName, "addAuthorization", new Object[] {"mx4j", "mx4j"}, new String[] {"java.lang.String", "java.lang.String"});

   // use basic authentication
   //server.setAttribute(serverName, new Attribute("AuthenticationMethod", "basic"));

   // SSL support
   ObjectName sslFactory = new ObjectName("Adaptor:service=SSLServerSocketFactory");
   server.createMBean("mx4j.tools.adaptor.ssl.SSLAdaptorServerSocketFactory", sslFactory, null);

   SSLAdaptorServerSocketFactoryMBean factory = (SSLAdaptorServerSocketFactoryMBean)MBeanServerInvocationHandler.newProxyInstance(server, sslFactory, SSLAdaptorServerSocketFactoryMBean.class, false);
   // Customize the values below
   factory.setKeyStoreName("certs");
   factory.setKeyStorePassword("mx4j");

   server.setAttribute(serverName, new Attribute("SocketFactoryName", sslFactory));

   // starts the server
   server.invoke(serverName, "start", null, null);
}
 
Example 16
Source File: CounterMonitorThresholdTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void runTest(int offset,
                           int counter[],
                           int derivedGauge[],
                           int threshold[]) throws Exception {
    // Retrieve the platform MBean server
    //
    System.out.println("\nRetrieve the platform MBean server");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = mbs.getDefaultDomain();

    // Create and register TestMBean
    //
    ObjectName name =
        new ObjectName(domain +
                       ":type=" + Test.class.getName() +
                       ",offset=" + offset);
    mbs.createMBean(Test.class.getName(), name);
    TestMBean mbean = (TestMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, name, TestMBean.class, false);

    // Create and register CounterMonitorMBean
    //
    ObjectName cmn =
        new ObjectName(domain +
                       ":type=" + CounterMonitor.class.getName() +
                       ",offset=" + offset);
    CounterMonitor m = new CounterMonitor();
    mbs.registerMBean(m, cmn);
    CounterMonitorMBean cm = (CounterMonitorMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, cmn, CounterMonitorMBean.class, true);
    ((NotificationEmitter) cm).addNotificationListener(
        new Listener(), null, null);
    cm.addObservedObject(name);
    cm.setObservedAttribute("Counter");
    cm.setGranularityPeriod(100);
    cm.setInitThreshold(1);
    cm.setOffset(offset);
    cm.setModulus(5);
    cm.setNotify(true);

    // Start the monitor
    //
    System.out.println("\nStart monitoring...");
    cm.start();

    // Play with counter
    //
    for (int i = 0; i < counter.length; i++) {
        mbean.setCounter(counter[i]);
        System.out.println("\nCounter = " + mbean.getCounter());
        Integer derivedGaugeValue;
        // either pass or test timeout (killed by test harness)
        // see 8025207
        do {
            Thread.sleep(150);
            derivedGaugeValue = (Integer) cm.getDerivedGauge(name);
        } while (derivedGaugeValue.intValue() != derivedGauge[i]);

        Number thresholdValue = cm.getThreshold(name);
        System.out.println("Threshold = " + thresholdValue);
        if (thresholdValue.intValue() != threshold[i]) {
            System.out.println("Wrong threshold! Current value = " +
                thresholdValue + " Expected value = " + threshold[i]);
            System.out.println("\nStop monitoring...");
            cm.stop();
            throw new IllegalArgumentException("wrong threshold");
        }
    }

    // Stop the monitor
    //
    System.out.println("\nStop monitoring...");
    cm.stop();
}
 
Example 17
Source File: OpenwireArtemisBaseTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private static Object createProxy(final ObjectName objectName,
                                  final Class mbeanInterface,
                                  final MBeanServer mbeanServer) {
   return MBeanServerInvocationHandler.newProxyInstance(mbeanServer, objectName, mbeanInterface, false);
}
 
Example 18
Source File: CounterMonitorThresholdTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void runTest(int offset,
                           int counter[],
                           int derivedGauge[],
                           int threshold[]) throws Exception {
    // Retrieve the platform MBean server
    //
    System.out.println("\nRetrieve the platform MBean server");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = mbs.getDefaultDomain();

    // Create and register TestMBean
    //
    ObjectName name =
        new ObjectName(domain +
                       ":type=" + Test.class.getName() +
                       ",offset=" + offset);
    mbs.createMBean(Test.class.getName(), name);
    TestMBean mbean = (TestMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, name, TestMBean.class, false);

    // Create and register CounterMonitorMBean
    //
    ObjectName cmn =
        new ObjectName(domain +
                       ":type=" + CounterMonitor.class.getName() +
                       ",offset=" + offset);
    CounterMonitor m = new CounterMonitor();
    mbs.registerMBean(m, cmn);
    CounterMonitorMBean cm = (CounterMonitorMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, cmn, CounterMonitorMBean.class, true);
    ((NotificationEmitter) cm).addNotificationListener(
        new Listener(), null, null);
    cm.addObservedObject(name);
    cm.setObservedAttribute("Counter");
    cm.setGranularityPeriod(100);
    cm.setInitThreshold(1);
    cm.setOffset(offset);
    cm.setModulus(5);
    cm.setNotify(true);

    // Start the monitor
    //
    System.out.println("\nStart monitoring...");
    cm.start();

    // Play with counter
    //
    for (int i = 0; i < counter.length; i++) {
        mbean.setCounter(counter[i]);
        System.out.println("\nCounter = " + mbean.getCounter());
        Integer derivedGaugeValue;
        // either pass or test timeout (killed by test harness)
        // see 8025207
        do {
            Thread.sleep(150);
            derivedGaugeValue = (Integer) cm.getDerivedGauge(name);
        } while (derivedGaugeValue.intValue() != derivedGauge[i]);

        Number thresholdValue = cm.getThreshold(name);
        System.out.println("Threshold = " + thresholdValue);
        if (thresholdValue.intValue() != threshold[i]) {
            System.out.println("Wrong threshold! Current value = " +
                thresholdValue + " Expected value = " + threshold[i]);
            System.out.println("\nStop monitoring...");
            cm.stop();
            throw new IllegalArgumentException("wrong threshold");
        }
    }

    // Stop the monitor
    //
    System.out.println("\nStop monitoring...");
    cm.stop();
}
 
Example 19
Source File: CounterMonitorThresholdTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void runTest(int offset,
                           int counter[],
                           int derivedGauge[],
                           int threshold[]) throws Exception {
    // Retrieve the platform MBean server
    //
    System.out.println("\nRetrieve the platform MBean server");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = mbs.getDefaultDomain();

    // Create and register TestMBean
    //
    ObjectName name =
        new ObjectName(domain +
                       ":type=" + Test.class.getName() +
                       ",offset=" + offset);
    mbs.createMBean(Test.class.getName(), name);
    TestMBean mbean = (TestMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, name, TestMBean.class, false);

    // Create and register CounterMonitorMBean
    //
    ObjectName cmn =
        new ObjectName(domain +
                       ":type=" + CounterMonitor.class.getName() +
                       ",offset=" + offset);
    CounterMonitor m = new CounterMonitor();
    mbs.registerMBean(m, cmn);
    CounterMonitorMBean cm = (CounterMonitorMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, cmn, CounterMonitorMBean.class, true);
    ((NotificationEmitter) cm).addNotificationListener(
        new Listener(), null, null);
    cm.addObservedObject(name);
    cm.setObservedAttribute("Counter");
    cm.setGranularityPeriod(100);
    cm.setInitThreshold(1);
    cm.setOffset(offset);
    cm.setModulus(5);
    cm.setNotify(true);

    // Start the monitor
    //
    System.out.println("\nStart monitoring...");
    cm.start();

    // Play with counter
    //
    for (int i = 0; i < counter.length; i++) {
        mbean.setCounter(counter[i]);
        System.out.println("\nCounter = " + mbean.getCounter());
        Integer derivedGaugeValue;
        // either pass or test timeout (killed by test harness)
        // see 8025207
        do {
            Thread.sleep(150);
            derivedGaugeValue = (Integer) cm.getDerivedGauge(name);
        } while (derivedGaugeValue.intValue() != derivedGauge[i]);

        Number thresholdValue = cm.getThreshold(name);
        System.out.println("Threshold = " + thresholdValue);
        if (thresholdValue.intValue() != threshold[i]) {
            System.out.println("Wrong threshold! Current value = " +
                thresholdValue + " Expected value = " + threshold[i]);
            System.out.println("\nStop monitoring...");
            cm.stop();
            throw new IllegalArgumentException("wrong threshold");
        }
    }

    // Stop the monitor
    //
    System.out.println("\nStop monitoring...");
    cm.stop();
}
 
Example 20
Source File: CounterMonitorThresholdTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void runTest(int offset,
                           int counter[],
                           int derivedGauge[],
                           int threshold[]) throws Exception {
    // Retrieve the platform MBean server
    //
    System.out.println("\nRetrieve the platform MBean server");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    String domain = mbs.getDefaultDomain();

    // Create and register TestMBean
    //
    ObjectName name =
        new ObjectName(domain +
                       ":type=" + Test.class.getName() +
                       ",offset=" + offset);
    mbs.createMBean(Test.class.getName(), name);
    TestMBean mbean = (TestMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, name, TestMBean.class, false);

    // Create and register CounterMonitorMBean
    //
    ObjectName cmn =
        new ObjectName(domain +
                       ":type=" + CounterMonitor.class.getName() +
                       ",offset=" + offset);
    CounterMonitor m = new CounterMonitor();
    mbs.registerMBean(m, cmn);
    CounterMonitorMBean cm = (CounterMonitorMBean)
        MBeanServerInvocationHandler.newProxyInstance(
            mbs, cmn, CounterMonitorMBean.class, true);
    ((NotificationEmitter) cm).addNotificationListener(
        new Listener(), null, null);
    cm.addObservedObject(name);
    cm.setObservedAttribute("Counter");
    cm.setGranularityPeriod(100);
    cm.setInitThreshold(1);
    cm.setOffset(offset);
    cm.setModulus(5);
    cm.setNotify(true);

    // Start the monitor
    //
    System.out.println("\nStart monitoring...");
    cm.start();

    // Play with counter
    //
    for (int i = 0; i < counter.length; i++) {
        mbean.setCounter(counter[i]);
        System.out.println("\nCounter = " + mbean.getCounter());
        Integer derivedGaugeValue;
        // either pass or test timeout (killed by test harness)
        // see 8025207
        do {
            Thread.sleep(150);
            derivedGaugeValue = (Integer) cm.getDerivedGauge(name);
        } while (derivedGaugeValue.intValue() != derivedGauge[i]);

        Number thresholdValue = cm.getThreshold(name);
        System.out.println("Threshold = " + thresholdValue);
        if (thresholdValue.intValue() != threshold[i]) {
            System.out.println("Wrong threshold! Current value = " +
                thresholdValue + " Expected value = " + threshold[i]);
            System.out.println("\nStop monitoring...");
            cm.stop();
            throw new IllegalArgumentException("wrong threshold");
        }
    }

    // Stop the monitor
    //
    System.out.println("\nStop monitoring...");
    cm.stop();
}