예제 #1
0
  private static boolean test(String proto, MBeanServer mbs) throws Exception {
    System.out.println("Testing for proto " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXServiceURL rmiurl = new JMXServiceURL("rmi", null, 0);
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    ObjectName on = new ObjectName("x:proto=" + proto + ",ok=yes");
    mbsc.createMBean(
        RMIConnectorServer.class.getName(),
        on,
        mletName,
        new Object[] {rmiurl, null},
        new String[] {JMXServiceURL.class.getName(), Map.class.getName()});
    System.out.println("Successfully deserialized with " + proto);
    mbsc.unregisterMBean(on);

    client.close();
    cs.stop();
    return true;
  }
예제 #2
0
 @Test
 public void createDestroyViaMBean() throws Exception {
   JMXConnector connector = null;
   try {
     connector = this.getJMXConnector();
     MBeanServerConnection connection = connector.getMBeanServerConnection();
     ObjectName name = new ObjectName("org.apache.karaf:type=instance,name=root");
     int oldNum = getInstancesNum(connection, name);
     connection.invoke(
         name,
         "createInstance",
         new Object[] {"itest2", 0, 0, 0, null, null, null, null},
         new String[] {
           "java.lang.String",
           "int",
           "int",
           "int",
           "java.lang.String",
           "java.lang.String",
           "java.lang.String",
           "java.lang.String"
         });
     Assert.assertEquals(oldNum + 1, getInstancesNum(connection, name));
     connection.invoke(
         name, "destroyInstance", new Object[] {"itest2"}, new String[] {"java.lang.String"});
     Assert.assertEquals(oldNum, getInstancesNum(connection, name));
   } finally {
     if (connector != null) close(connector);
   }
 }
  private boolean isPassiveStandBy(int jmxPort) {
    TCServerInfoMBean mbean = null;
    boolean isPassiveStandBy = false;
    JMXConnector jmxConnector = null;

    try {
      jmxConnector = JMXUtils.getJMXConnector("localhost", jmxPort);
      final MBeanServerConnection mbs = jmxConnector.getMBeanServerConnection();
      mbean =
          MBeanServerInvocationProxy.newMBeanProxy(
              mbs, L2MBeanNames.TC_SERVER_INFO, TCServerInfoMBean.class, false);
      isPassiveStandBy = mbean.isPassiveStandby();
    } catch (Exception e) {
      return false;
    } finally {
      if (jmxConnector != null) {
        try {
          jmxConnector.close();
        } catch (Exception e) {
          System.out.println(
              "Exception while trying to close the JMX connector for port no: " + jmxPort);
        }
      }
    }

    return isPassiveStandBy;
  }
  @Override
  public void run(String... args) throws Exception {
    // TODO Auto-generated method stub
    final AttachProvider attachProvider = AttachProvider.providers().get(0);

    VirtualMachineDescriptor descriptor = null;
    for (VirtualMachineDescriptor virtualMachineDescriptor : attachProvider.listVirtualMachines()) {

      if (virtualMachineDescriptor.displayName().equals(applicationName)) {
        descriptor = virtualMachineDescriptor;
      }
    }
    final VirtualMachine virtualMachine = attachProvider.attachVirtualMachine(descriptor);
    virtualMachine.loadAgent(managmentAgentJar, "com.sun.management.jmxremote");
    final Object portObject =
        virtualMachine
            .getAgentProperties()
            .get("com.sun.management.jmxremote.localConnectorAddress");

    final JMXServiceURL target = new JMXServiceURL(portObject + "");
    final JMXConnector connector = JMXConnectorFactory.connect(target);
    final MBeanServerConnection remote = connector.getMBeanServerConnection();

    final ObjectName objectName =
        new ObjectName("Catalina:type=Manager,host=localhost,context=" + context);
    System.out.println("Start");

    System.out.println("ActiveSession = " + remote.getAttribute(objectName, "activeSessions"));
    System.out.println("End");
  }
예제 #5
0
  public static void main(String[] args)
      throws MalformedURLException, IOException, MalformedObjectNameException {
    try {
      // Get MbeanServerConnection
      MBeanServerConnection mbc;
      JMXServiceURL url = new JMXServiceURL(JMX_URI);
      JMXConnector jmxcon = JMXConnectorFactory.connect(url, null);
      mbc = jmxcon.getMBeanServerConnection();

      // Get GC Collectors
      Iterator<ObjectName> itr = mbc.queryNames(null, null).iterator();
      ArrayList gcList = new ArrayList();

      while (itr.hasNext()) {
        String matchedName = itr.next().toString();
        if (matchedName.indexOf("GarbageCollector") > 0) {
          gcList.add(matchedName);
        }
      }
      System.out.println(gcList);

      // Fetch GC type collection time
      for (int i = 0; i < gcList.size(); i++) {
        ObjectName queryName = new ObjectName(gcList.get(i).toString());
        System.out.print(queryName + ":");
        System.out.println(mbc.getAttribute(queryName, "CollectionTime"));
      }

      ObjectName uptimeName = new ObjectName("java.lang:type=Runtime");
      System.out.print("Server Uptime" + ":");
      System.out.print(mbc.getAttribute(uptimeName, "Uptime"));
      System.out.println(" Seconds");

      // Fetch heap Memory usage stat
      // committed=523501568, max=523501568, used=106156848
      CompositeDataSupport cdsHeap;
      ObjectName heapMemoryUsage = new ObjectName("java.lang:type=Memory");
      System.out.println(
          cdsHeap = (CompositeDataSupport) mbc.getAttribute(heapMemoryUsage, "HeapMemoryUsage"));
      System.out.println(cdsHeap.get("used"));

      // Fetch nonheap Memory usage stat
      // committed=523501568, max=523501568, used=106156848
      CompositeDataSupport cdsNonHeap;
      ObjectName nonHeapMemoryUsage = new ObjectName("java.lang:type=Memory");
      System.out.println(
          cdsNonHeap =
              (CompositeDataSupport) mbc.getAttribute(nonHeapMemoryUsage, "NonHeapMemoryUsage"));
      System.out.println(cdsNonHeap.get("used"));

    } catch (MBeanException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (AttributeNotFoundException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstanceNotFoundException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ReflectionException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
예제 #6
0
 private void waitForForkedSpringApplication()
     throws IOException, MojoFailureException, MojoExecutionException {
   try {
     getLog().debug("Connecting to local MBeanServer at port " + this.jmxPort);
     JMXConnector connector =
         execute(this.wait, this.maxAttempts, new CreateJmxConnector(this.jmxPort));
     if (connector == null) {
       throw new MojoExecutionException(
           "JMX MBean server was not reachable before the configured "
               + "timeout ("
               + (this.wait * this.maxAttempts)
               + "ms");
     }
     getLog().debug("Connected to local MBeanServer at port " + this.jmxPort);
     try {
       MBeanServerConnection connection = connector.getMBeanServerConnection();
       doWaitForSpringApplication(connection);
     } finally {
       connector.close();
     }
   } catch (IOException ex) {
     throw ex;
   } catch (Exception ex) {
     throw new MojoExecutionException(
         "Failed to connect to MBean server at port " + this.jmxPort, ex);
   }
 }
예제 #7
0
  @Test
  public void testDigestAuthentication() throws Exception {
    log.info("testDigestAuthentication - Begin");
    config.saslMechanisms = Collections.singleton(DIGEST_MD5);

    JMXRemotingServer remotingServer = new JMXRemotingServer(config);
    remotingServer.start();

    Map<String, Object> env = new HashMap<String, Object>(1);
    env.put(JMXConnector.CREDENTIALS, new String[] {"DigestUser", "DigestPassword"});

    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, env);

    assertNotNull(connector.getConnectionId());

    connector.close();

    // Now Try A Bad Password
    env.put(JMXConnector.CREDENTIALS, new String[] {"DigestUser", "BadPassword"});
    try {
      JMXConnectorFactory.connect(serviceURL, env);
      fail("Expected exception not thrown.");
    } catch (IOException expected) {
    }

    remotingServer.stop();
  }
예제 #8
0
 @Test
 public void renameViaMBean() throws Exception {
   JMXConnector connector = null;
   try {
     connector = this.getJMXConnector();
     MBeanServerConnection connection = connector.getMBeanServerConnection();
     ObjectName name = new ObjectName("org.apache.karaf:type=instance,name=root");
     connection.invoke(
         name,
         "createInstance",
         new Object[] {"itest5", 0, 0, 0, null, null, null, null},
         new String[] {
           "java.lang.String",
           "int",
           "int",
           "int",
           "java.lang.String",
           "java.lang.String",
           "java.lang.String",
           "java.lang.String"
         });
     connection.invoke(
         name,
         "renameInstance",
         new Object[] {"itest5", "new_itest5"},
         new String[] {"java.lang.String", "java.lang.String"});
   } finally {
     if (connector != null) connector.close();
   }
 }
  public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorNullSubjectConnTest starting...");

    JMXConnectorServer connectorServer = null;
    JMXConnector connectorClient = null;

    try {
      MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
      JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
      connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
      connectorServer.start();

      JMXServiceURL serverAddr = connectorServer.getAddress();
      connectorClient = JMXConnectorFactory.connect(serverAddr, null);
      connectorClient.connect();

      Field nullSubjectConnField = RMIConnector.class.getDeclaredField("nullSubjectConnRef");
      nullSubjectConnField.setAccessible(true);

      WeakReference<MBeanServerConnection> weak =
          (WeakReference<MBeanServerConnection>) nullSubjectConnField.get(connectorClient);

      if (weak != null && weak.get() != null) {
        throw new RuntimeException("nullSubjectConnRef must be null at initial time.");
      }

      MBeanServerConnection conn1 = connectorClient.getMBeanServerConnection(null);
      MBeanServerConnection conn2 = connectorClient.getMBeanServerConnection(null);
      if (conn1 == null) {
        throw new RuntimeException("A connection with null subject should not be null.");
      } else if (conn1 != conn2) {
        throw new RuntimeException("The 2 connections with null subject are not equal.");
      }

      conn1 = null;
      conn2 = null;
      int i = 1;
      do {
        System.gc();
        Thread.sleep(100);
        weak = (WeakReference<MBeanServerConnection>) nullSubjectConnField.get(connectorClient);
      } while ((weak != null && weak.get() != null) && i++ < 60);

      System.out.println("---GC times: " + i);

      if (weak != null && weak.get() != null) {
        throw new RuntimeException("Failed to clean RMIConnector's nullSubjectConn");
      } else {
        System.out.println("---RMIConnectorNullSubjectConnTest: PASSED!");
      }
    } finally {
      try {
        connectorClient.close();
        connectorServer.stop();
      } catch (Exception e) {
      }
    }
  }
예제 #10
0
  public JMXLocalConnector(String serviceURL) {
    try {
      final JMXServiceURL jmxServiceUrl = new JMXServiceURL(serviceURL);
      final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, null);

      mBeanServerConnection = jmxConnector.getMBeanServerConnection();
    } catch (Exception e) {
      throw new IllegalArgumentException("Unable to get JMX connection", e);
    }
  }
예제 #11
0
  private static void test(String proto) throws Exception {
    System.out.println(">>> Test for protocol " + proto);

    JMXServiceURL u = null;
    JMXConnectorServer server = null;

    HashMap env = new HashMap(2);
    // server will close a client connection after 1 second
    env.put("jmx.remote.x.server.connection.timeout", "1000");

    // disable the client ping
    env.put("jmx.remote.x.client.connection.check.period", "0");

    try {
      u = new JMXServiceURL(proto, null, 0);
      server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs);
    } catch (MalformedURLException e) {
      System.out.println(">>> Skipping unsupported URL " + proto);
    }

    server.start();

    JMXServiceURL addr = server.getAddress();

    long st = 2000;
    MyListener myListener;

    // a cycle to make sure that we test the blocking problem.
    do {
      JMXConnector client = JMXConnectorFactory.connect(addr, env);
      MBeanServerConnection conn = client.getMBeanServerConnection();
      myListener = new MyListener(conn);
      client.addConnectionNotificationListener(myListener, null, null);

      // wait the server to close the client connection
      Thread.sleep(st);

      // makes the listener to do a remote request via the connection
      // which should be closed by the server.
      conn.getDefaultDomain();

      // allow the listner to have time to work
      Thread.sleep(100);

      // get a closed notif, should no block.
      client.close();
      Thread.sleep(100);

      st += 2000;

    } while (!myListener.isDone());

    server.stop();
  }
 private MBeanServerConnection reconnect() {
   try {
     final Map<String, Object> env = new HashMap<>();
     env.put(CallbackHandler.class.getName(), Authentication.getCallbackHandler());
     final JMXConnector connector =
         ManagementClient.this.connector = JMXConnectorFactory.connect(getRemoteJMXURL(), env);
     connection = connector.getMBeanServerConnection();
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return connection;
 }
  public static void main(String[] args) throws IOException {
    JMXServiceURL address =
        new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi");
    JMXConnector connector = JMXConnectorFactory.connect(address);

    MBeanServerConnection msc = connector.getMBeanServerConnection();

    HotSpotDiagnosticMXBean hotspot =
        ManagementFactory.newPlatformMXBeanProxy(
            msc, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
    hotspot.dumpHeap("out.txt", true);
  }
예제 #14
0
 @Test
 public void testMBean() throws Exception {
   final JMXConnector connector = JMXConnectorFactory.connect(managementClient.getRemoteJMXURL());
   try {
     MBeanServerConnection mbeanServer = connector.getMBeanServerConnection();
     ObjectName objectName = new ObjectName("jboss:name=test,type=config");
     mbeanServer.getAttribute(objectName, "IntervalSeconds");
     mbeanServer.setAttribute(objectName, new Attribute("IntervalSeconds", 2));
   } finally {
     IoUtils.safeClose(connector);
   }
 }
  @Nonnull
  protected MBeanServerConnection connectToMbeanServer(@Nonnull String pid) throws IOException {
    VirtualMachine vm;
    try {
      Integer.parseInt(pid);
    } catch (Exception e) {
      logger.warn("Exception parsing PID '{}'", pid, e);
    }
    try {
      vm = VirtualMachine.attach(pid);
    } catch (Exception e) {
      throw new IllegalStateException("Exception attaching VM with PID '" + pid + "'", e);
    }

    logger.trace("VM Agent Properties");
    for (String key : new TreeSet<String>(vm.getAgentProperties().stringPropertyNames())) {
      logger.trace("\t {}: {}", key, vm.getAgentProperties().get(key));
    }
    logger.trace("VM System Properties");
    for (String key : new TreeSet<String>(vm.getSystemProperties().stringPropertyNames())) {
      logger.trace("\t {}: {}", key, vm.getSystemProperties().get(key));
    }

    String connectorAddress =
        vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    if (connectorAddress == null) {
      String agent =
          vm.getSystemProperties().getProperty("java.home")
              + File.separator
              + "lib"
              + File.separator
              + "management-agent.jar";
      try {
        vm.loadAgent(agent);
      } catch (Exception e) {
        throw new IllegalStateException("Exception loading agent " + agent);
      }
      connectorAddress =
          vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    }

    if (connectorAddress == null) {
      throw new IllegalStateException(
          "Could not attach to pid: " + pid + ". No connector available");
    }
    logger.trace("Connect to {} ...", connectorAddress);

    JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(connectorAddress));

    return connector.getMBeanServerConnection();
  }
예제 #16
0
    private void tryConnect() throws IOException {
      if (mode == MODE_SELF) {
        jmxc = null;
        conn = ManagementFactory.getPlatformMBeanServer();
      } else {
        if (mode == MODE_LOCAL) {
          if (!lvm.isManageable()) {
            lvm.startManagementAgent();
            if (!lvm.isManageable()) {
              // FIXME: what to throw
              throw new IOException(lvm + " not manageable"); // NOI18N
            }
          }
          if (jmxUrl == null) {
            jmxUrl = new JMXServiceURL(lvm.connectorAddress());
          }
        }

        Map<String, Object> env = new HashMap();
        if (envProvider != null) env.putAll(envProvider.getEnvironment(app, app.getStorage()));
        if (userName != null || password != null)
          env.put(JMXConnector.CREDENTIALS, new String[] {userName, password});

        if (!insecure && mode != MODE_LOCAL && env.get(JMXConnector.CREDENTIALS) != null) {
          env.put("jmx.remote.x.check.stub", "true"); // NOI18N
          checkSSLStub = true;
        } else {
          checkSSLStub = false;
        }

        jmxc = JMXConnectorFactory.newJMXConnector(jmxUrl, env);
        jmxc.addConnectionNotificationListener(this, null, null);
        try {
          jmxc.connect(env);
        } catch (java.io.IOException e) {
          // Likely a SSL-protected RMI registry
          if ("rmi".equals(jmxUrl.getProtocol())) { // NOI18N
            env.put("com.sun.jndi.rmi.factory.socket", sslRMIClientSocketFactory); // NOI18N
            jmxc.connect(env);
          } else {
            throw e;
          }
        }

        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        conn = Checker.newChecker(this, mbsc);
      }
      isDead = false;
    }
  static boolean execScript(String process, String script) {
    int vmid = -1;
    try {
      vmid = Integer.parseInt(process);
    } catch (NumberFormatException e) {
      vmid = findVmid(process);
    }
    if (vmid == -1) {
      System.err.println(process + ": Could not find process");
      return false;
    }

    try {
      JMXConnector jmxc;
      MBeanServerConnection server;

      String address = ConnectorAddressLink.importFrom(vmid);
      JMXServiceURL jmxUrl = new JMXServiceURL(address);
      jmxc = JMXConnectorFactory.connect(jmxUrl);
      server = jmxc.getMBeanServerConnection();
      Object[] parameters = {script};
      String[] signature = {"java.lang.String"};
      Object result;
      result =
          server.invoke(
              new ObjectName("net.multiverse:type=Engine"),
              "runPythonScript",
              parameters,
              signature);
      System.out.println(result.toString());
      jmxc.close();
    } catch (IOException e) {
      System.err.println("Unable to attach to " + vmid + ": " + e.getMessage());
      return false;
    } catch (javax.management.MalformedObjectNameException e) {
      System.err.println("Internal error: " + e.getMessage());
      return false;
    } catch (javax.management.InstanceNotFoundException e) {
      System.err.println("Process " + vmid + " is not a Multiverse engine");
      return false;
    } catch (javax.management.MBeanException e) {
      System.err.println("Error: " + e);
      return false;
    } catch (javax.management.ReflectionException e) {
      System.err.println("Error: " + e);
      return false;
    }
    return true;
  }
예제 #18
0
  public static void main(String[] args) throws Exception {
    // Get a connection to the JBoss AS MBean server on localhost
    String host = "localhost";
    int port = 1090;
    String urlString =
        System.getProperty(
            "jmx.service.url", "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
    MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();

    // Invoke on the JBoss AS MBean server
    int count = connection.getMBeanCount();
    System.out.println(count);
  }
 private void initializeAdminConnector() throws IOException, MalformedObjectNameException {
   String username = properties.getProperty("userName");
   String password = properties.getProperty("password");
   Map<String, String[]> env = new HashMap<>();
   String[] credentials = new String[] {username, password};
   env.put(JMXConnector.CREDENTIALS, credentials);
   String serviceURL = properties.getProperty("jmxURL");
   connector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL(serviceURL), env);
   connector.connect();
   MBeanServerConnection connection = connector.getMBeanServerConnection();
   ObjectName activeMQ = new ObjectName("org.apache.activemq:type=Broker,brokerName=amq-broker");
   adminMBean =
       MBeanServerInvocationHandler.newProxyInstance(
           connection, activeMQ, BrokerViewMBean.class, true);
 }
예제 #20
0
  public void init() throws Exception {

    super.init();

    url = getParameter(URL);

    if (url == null) {
      protocol = getParameter(PROTOCOL);
      host = getParameter(HOST);
      port = Integer.parseInt(getParameter(PORT));
      transportPort = Integer.parseInt(getParameter(TRANSPORT_PORT));

      url = "service:jmx:" + protocol + "://" + host;
      if (transportPort != DEFAULT_TRANSPORT_PORT) url += ":" + transportPort;

      url += "/jndi/" + protocol + "://" + host;
      if (port != DEFAULT_PORT) url += ":" + port;

      url += "/penrose";

      // url =
      // "service:jmx:rmi://localhost:rmiTransportProtocol/jndi/rmi://localhost:rmiProtocol/penrose";
    }

    bindDn = getParameter(BIND_DN);
    log.debug("Bind DN: " + bindDn);

    bindPassword = getParameter(BIND_PASSWORD);
    log.debug("Password: "******"java.lang:type=Memory");

    Hashtable<String, Object> parameters = new Hashtable<String, Object>();

    if (bindDn != null && bindPassword != null) {
      log.debug("Binding as " + bindDn + ".");

      String[] credentials = new String[] {bindDn, bindPassword};

      parameters.put(JMXConnector.CREDENTIALS, credentials);
    }

    JMXServiceURL serviceURL = new JMXServiceURL(url);
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, parameters);

    connection = connector.getMBeanServerConnection();
    connection.addNotificationListener(memoryMBean, this, null, null);
  }
예제 #21
0
 public void run() {
   try {
     m_connector.close();
   } catch (Exception e) {
     /**/
   }
 }
예제 #22
0
 /**
  * connect to org.wso2.carbon to invoke different operations
  *
  * @param userName user name to connect to org.wso2.carbon
  * @param password password to connect to org.wso2.carbon
  * @param connectionType
  * @param operation
  * @throws Exception
  */
 public void connect(String userName, String password, String connectionType, String operation)
     throws Exception {
   try {
     JMXServiceURL url =
         new JMXServiceURL(
             "service:jmx:rmi://"
                 + NetworkUtils.getLocalHostname()
                 + ":"
                 + RMIServerPort
                 + "/jndi/rmi://"
                 + NetworkUtils.getLocalHostname()
                 + ":"
                 + RMIRegistryPort
                 + "/jmxrmi");
     Hashtable<String, String[]> hashT = new Hashtable<String, String[]>();
     String[] credentials = new String[] {userName, password};
     hashT.put("jmx.remote.credentials", credentials);
     jmxc = JMXConnectorFactory.connect(url, hashT);
     mbsc = jmxc.getMBeanServerConnection();
     nodeAgent = new ObjectName(connectionType);
     mbsc.invoke(nodeAgent, operation, null, null);
   } catch (Exception ex) {
     log.error("infoAdminServiceStub Initialization fail ");
     throw new Exception("infoAdminServiceStub Initialization fail " + ex.getMessage());
   }
 }
 @BeforeClass
 public static void beforeClass() throws Exception {
   runtimeType = RuntimeType.getRuntimeType(System.getProperty("target.container"));
   if (runtimeType == RuntimeType.KARAF) {
     String jmxServiceURL =
         "service:jmx:rmi://127.0.0.1:44444/jndi/rmi://127.0.0.1:1099/karaf-root";
     Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL);
     env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]});
     connector = ManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS);
   } else if (runtimeType == RuntimeType.TOMCAT) {
     String jmxServiceURL = "service:jmx:rmi:///jndi/rmi://127.0.0.1:8089/jmxrmi";
     Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL);
     env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]});
     connector = ManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS);
   } else if (runtimeType == RuntimeType.WILDFLY) {
     String jmxServiceURL = "service:jmx:http-remoting-jmx://127.0.0.1:9990";
     Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL);
     env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]});
     connector = WildFlyManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS);
   } else {
     throw new IllegalStateException("Usupported target container: " + runtimeType);
   }
   proxy =
       JMX.newMXBeanProxy(
           connector.getMBeanServerConnection(),
           ProfileManagement.OBJECT_NAME,
           ProfileManagement.class);
 }
예제 #24
0
 public void disconnect() {
   // Reset remote stub
   stub = null;
   // Close MBeanServer connection
   if (jmxc != null) {
     try {
       jmxc.close();
     } catch (IOException e) {
       // Ignore ???
     }
   }
   // Reset platform MBean references
   classLoadingMBean = null;
   compilationMBean = null;
   memoryMBean = null;
   operatingSystemMBean = null;
   runtimeMBean = null;
   threadMBean = null;
   sunOperatingSystemMXBean = null;
   garbageCollectorMBeans = null;
   // Set connection state to DISCONNECTED
   if (!isDead) {
     isDead = true;
     setConnectionState(ConnectionState.DISCONNECTED);
   }
 }
예제 #25
0
  public boolean verifyJmxRmiConnection() {
    boolean result = false;

    // Typically the JMXServiceURL looks something like this:
    //  "service:jmx:rmi://ignored/jndi/rmi://localhost:50501/alfresco/jmxrmi"

    if (getVirtServerJmxUrl() == null) {
      if (log.isWarnEnabled()) log.warn("No virtualization servers have registered as listeners");

      return result;
    }

    if (conn_ == null) {
      try {
        conn_ = JMXConnectorFactory.connect(getJMXServiceURL(), env_);
        mbsc_ = conn_.getMBeanServerConnection();
      } catch (Exception e) {
        if (log.isErrorEnabled())
          log.error("Could not connect to virtualization server: " + getVirtServerJmxUrl());

        return result;
      }
    }
    // If virtualization server have been terminated (E.g. Control+C in the console)
    // virtServerJmxUrl_ is not null and conn_ is not null so it is impossible to detect
    // terminated/refused
    // connection. Just check connection to accessibility.
    else {
      result = pingVirtServer();
    }
    return result;
  }
예제 #26
0
 /** @param args */
 public static void main(String[] args) throws Exception {
   JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
   JMXConnector connector = JMXConnectorFactory.connect(url, null);
   connector.connect();
   MBeanServerConnection connection = connector.getMBeanServerConnection();
   String brokerName = "localhost";
   String connectionName = "ID_dejan-bosanacs-macbook-pro.local-50462-1236596709533-3_0";
   ObjectName query =
       new ObjectName(
           "org.apache.activemq:BrokerName="
               + brokerName
               + ",Type=Connection,*,Connection="
               + connectionName);
   Set<ObjectName> queryResult = connection.queryNames(query, null);
   System.out.println(queryResult);
 }
 // @TODO arrange to close the connection? At what point?
 public void dispose() {
   try {
     jmxConnector.close();
   } catch (IOException e) {
     // safe to ignore this exception - may get here if server process dies before JMX connection
     // is destroyed
   }
 }
예제 #28
0
 public void run() {
   try {
     if (conn_ != null) {
       conn_.close();
     }
   } catch (Exception e) {
   }
 }
예제 #29
0
  private static void test() {
    try {
      JMXServiceURL u = new JMXServiceURL("rmi", null, 0);
      JMXConnectorServer server;
      JMXServiceURL addr;
      JMXConnector client;
      MBeanServerConnection mserver;

      final ObjectName delegateName = new ObjectName("JMImplementation:type=MBeanServerDelegate");
      final NotificationListener dummyListener =
          new NotificationListener() {
            public void handleNotification(Notification n, Object o) {
              // do nothing
              return;
            }
          };

      server = JMXConnectorServerFactory.newJMXConnectorServer(u, null, mbs);
      server.start();

      addr = server.getAddress();
      client = JMXConnectorFactory.newJMXConnector(addr, null);
      client.connect(null);

      mserver = client.getMBeanServerConnection();
      String s1 = "1";
      String s2 = "2";
      String s3 = "3";

      mserver.addNotificationListener(delegateName, dummyListener, null, s1);
      mserver.addNotificationListener(delegateName, dummyListener, null, s2);
      mserver.addNotificationListener(delegateName, dummyListener, null, s3);

      mserver.removeNotificationListener(delegateName, dummyListener, null, s3);
      mserver.removeNotificationListener(delegateName, dummyListener, null, s2);
      mserver.removeNotificationListener(delegateName, dummyListener, null, s1);
      client.close();

      server.stop();
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      System.exit(1);
    }
  }
예제 #30
0
 private void connectClient() throws IOException, TimeoutException {
   if (jmxUrl == null || ("localhost".equals(jmxUrl.getHost()) && jmxUrl.getPort() == 0)) {
     mbeanServerConnection = ManagementFactory.getPlatformMBeanServer();
   } else {
     jmxConnector = connectWithTimeout(jmxUrl, timeout);
     mbeanServerConnection = jmxConnector.getMBeanServerConnection();
   }
   this.connected = true;
 }