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;
    }
  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) {
      }
    }
  }
 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);
 }
 /** @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);
 }
Esempio n. 5
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);
    }
  }
Esempio n. 6
0
  @Override
  protected void process(PlungerArguments pa) throws CommandException {
    try {
      connector.connect();
      MBeanServerConnection connection = connector.getMBeanServerConnection();

      ObjectName nameList = new ObjectName("org.apache.activemq:brokerName=localhost,type=Broker");
      BrokerViewMBean mbList =
          MBeanServerInvocationHandler.newProxyInstance(
              connection, nameList, BrokerViewMBean.class, true);

      for (JmxDestination jd : new JmxDestinations(mbList)) {
        boolean matchesTarget =
            pa.getTarget().isDestinationErased()
                || jd.getDisplayName().equals(pa.getTarget().getDestination());
        if (matchesTarget) {
          ObjectName nameConsumers =
              new ObjectName(
                  "org.apache.activemq:type=Broker,brokerName=localhost,destinationType="
                      + jd.getDestinationType()
                      + ",destinationName="
                      + jd.getObjectName());
          DestinationViewMBean mbView =
              MBeanServerInvocationHandler.newProxyInstance(
                  connection, nameConsumers, DestinationViewMBean.class, true);
          if (!startsWith(jd.getObjectName(), "ActiveMQ.Advisory.")) {
            printDestination(
                pa,
                jd.getDisplayName(),
                mbView.getConsumerCount(),
                mbView.getQueueSize(),
                !jd.isTemporary());
          }
        }
      }
    } catch (Exception ex) {
      throw new CommandException("Failed retrieving ActiveMQ destinations", ex);
    }
  }
Esempio n. 7
0
  /**
   * Program Main.
   *
   * <p>Lookup all JMX agents in the LDAP Directory and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Dprotocol=&lt;ProtocolType&gt;</code>: restrains the client to lookup for a
   *       specific protocol type (default is null, meaning any type).
   *   <li><code>-Djava.naming.factory.initial=&lt;initial-context-factory&gt;
   *     </code>: The initial context factory to use for accessing the LDAP directory (see {@link
   *       Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY}) - default is <code>
   *       "com.sun.jndi.ldap.LdapCtxFactory"</code>.
   *   <li><code>-Djava.naming.provider.url=&lt;provider-url&gt;</code>: The LDAP Provider URL (see
   *       {@link Context#PROVIDER_URL Context.PROVIDER_URL}).
   *   <li><code>-Djava.naming.security.principal=&lt;ldap-principal&gt;
   *     </code>: The security principal (login) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_PRINCIPAL Context.SECURITY_PRINCIPAL} - default is <code>
   *       "cn=Directory Manager"</code>.
   *   <li><code>-Djava.naming.security.credentials=&lt;ldap-credentials&gt;
   *     </code>: The security credentials (password) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_CREDENTIALS Context.SECURITY_CREDENTIALS}).
   *   <li><code>-Ddebug="true|false"</code>: switch the Server debug flag on/off (default is
   *       "false")
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get a pointer to the LDAP Directory.
      //
      final DirContext root = getRootContext();
      debug("root is: " + root.getNameInNamespace());

      final String protocolType = System.getProperty("protocol");
      final String agentName = System.getProperty("agent.name");

      // Lookup all matching agents in the LDAP Directory.
      //
      List l = lookup(root, protocolType, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          // Prepare the environment Map
          //
          final HashMap env = new HashMap();
          final String factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
          final String ldapServerUrl = System.getProperty(Context.PROVIDER_URL);
          final String ldapUser = System.getProperty(Context.SECURITY_PRINCIPAL);
          final String ldapPasswd = System.getProperty(Context.SECURITY_CREDENTIALS);

          // Transfer some system properties to the Map
          //
          if (factory != null) // this should not be needed
          env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
          if (ldapServerUrl != null) // this should not be needed
          env.put(Context.PROVIDER_URL, ldapServerUrl);
          if (ldapUser != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_PRINCIPAL, ldapUser);
          if (ldapPasswd != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_CREDENTIALS, ldapPasswd);

          try {
            c1.connect(env);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
Esempio n. 8
0
  /**
   * Program Main
   *
   * <p>Lookup all JMX agents in the Jini Lookup Service and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Djini.lookup.url=&lt;jini-url&gt;</code>: the Jini Lookup Service URL (default is
   *       "jini://localhost"), see {@link #getRegistrar()}.
   *   <li><code>-Ddebug="true|false"</code>: switch the Client debug flag on/off (default is
   *       "false").
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Jini requires a security manager.
      //
      if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager());

      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get AgentName to lookup. If not defined, all agents
      // are looked up.
      //
      final String agentName = System.getProperty("agent.name");

      // Get a pointer to the Jini Lookup Service.
      //
      final ServiceRegistrar registrar = getRegistrar();
      debug("registrar is: " + registrar);

      // Lookup all matching agents in the Jini Lookup Service.
      //
      List l = lookup(registrar, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          try {
            c1.connect(null);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            if (debug) x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            if (debug) x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            if (debug) x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
  public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorInternalMapTest 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 rmbscMapField = RMIConnector.class.getDeclaredField("rmbscMap");
      rmbscMapField.setAccessible(true);
      Map<Subject, WeakReference<MBeanServerConnection>> map =
          (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
      if (map != null && !map.isEmpty()) { // failed
        throw new RuntimeException("RMIConnector's rmbscMap must be empty at the initial time.");
      }

      Subject delegationSubject =
          new Subject(
              true,
              Collections.singleton(new JMXPrincipal("delegate")),
              Collections.EMPTY_SET,
              Collections.EMPTY_SET);
      MBeanServerConnection mbsc1 = connectorClient.getMBeanServerConnection(delegationSubject);
      MBeanServerConnection mbsc2 = connectorClient.getMBeanServerConnection(delegationSubject);

      if (mbsc1 == null) {
        throw new RuntimeException("Got null connection.");
      }
      if (mbsc1 != mbsc2) {
        throw new RuntimeException("Not got same connection with a same subject.");
      }

      map = (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
      if (map == null || map.isEmpty()) { // failed
        throw new RuntimeException(
            "RMIConnector's rmbscMap has wrong size " + "after creating a delegated connection.");
      }

      delegationSubject = null;
      mbsc1 = null;
      mbsc2 = null;

      int i = 0;
      while (!map.isEmpty() && i++ < 60) {
        System.gc();
        Thread.sleep(100);
      }
      System.out.println("---GC times: " + i);

      if (!map.isEmpty()) {
        throw new RuntimeException("Failed to clean RMIConnector's rmbscMap");
      } else {
        System.out.println("---RMIConnectorInternalMapTest: PASSED!");
      }
    } finally {
      try {
        connectorClient.close();
        connectorServer.stop();
      } catch (Exception e) {
      }
    }
  }
Esempio n. 10
0
  private void tryConnect(boolean requireRemoteSSL) throws IOException {
    if (jmxUrl == null && "localhost".equals(hostName) && port == 0) {
      // Monitor self
      this.jmxc = null;
      this.mbsc = ManagementFactory.getPlatformMBeanServer();
      this.server = Snapshot.newSnapshot(mbsc);
    } else {
      // Monitor another process
      if (lvm != null) {
        if (!lvm.isManageable()) {
          lvm.startManagementAgent();
          if (!lvm.isManageable()) {
            // FIXME: what to throw
            throw new IOException(lvm + "not manageable");
          }
        }
        if (this.jmxUrl == null) {
          this.jmxUrl = new JMXServiceURL(lvm.connectorAddress());
        }
      }
      Map<String, Object> env = new HashMap<String, Object>();
      if (requireRemoteSSL) {
        env.put("jmx.remote.x.check.stub", "true");
      }
      // Need to pass in credentials ?
      if (userName == null && password == null) {
        if (isVmConnector()) {
          // Check for SSL config on reconnection only
          if (stub == null) {
            checkSslConfig();
          }
          this.jmxc = new RMIConnector(stub, null);
          jmxc.connect(env);
        } else {
          this.jmxc = JMXConnectorFactory.connect(jmxUrl, env);
        }
      } else {
        env.put(JMXConnector.CREDENTIALS, new String[] {userName, password});
        if (isVmConnector()) {
          // Check for SSL config on reconnection only
          if (stub == null) {
            checkSslConfig();
          }
          this.jmxc = new RMIConnector(stub, null);
          jmxc.connect(env);
        } else {
          this.jmxc = JMXConnectorFactory.connect(jmxUrl, env);
        }
      }
      this.mbsc = jmxc.getMBeanServerConnection();
      this.server = Snapshot.newSnapshot(mbsc);
    }
    this.isDead = false;

    try {
      ObjectName on = new ObjectName(THREAD_MXBEAN_NAME);
      this.hasPlatformMXBeans = server.isRegistered(on);
      this.hasHotSpotDiagnosticMXBean =
          server.isRegistered(new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME));
      // check if it has 6.0 new APIs
      if (this.hasPlatformMXBeans) {
        MBeanOperationInfo[] mopis = server.getMBeanInfo(on).getOperations();
        // look for findDeadlockedThreads operations;
        for (MBeanOperationInfo op : mopis) {
          if (op.getName().equals("findDeadlockedThreads")) {
            this.supportsLockUsage = true;
            break;
          }
        }

        on = new ObjectName(COMPILATION_MXBEAN_NAME);
        this.hasCompilationMXBean = server.isRegistered(on);
      }
    } catch (MalformedObjectNameException e) {
      // should not reach here
      throw new InternalError(e.getMessage());
    } catch (IntrospectionException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    } catch (InstanceNotFoundException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    } catch (ReflectionException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    }

    if (hasPlatformMXBeans) {
      // WORKAROUND for bug 5056632
      // Check if the access role is correct by getting a RuntimeMXBean
      getRuntimeMXBean();
    }
  }