Esempio n. 1
0
 public void run() {
   try {
     m_connector.close();
   } catch (Exception e) {
     /**/
   }
 }
Esempio n. 2
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);
   }
 }
Esempio n. 3
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);
   }
 }
  @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();
  }
Esempio n. 5
0
 @Test
 public void cloneViaMBean() 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,
         "cloneInstance",
         new Object[] {"root", "itest4", 0, 0, 0, null, null},
         new String[] {
           "java.lang.String",
           "java.lang.String",
           "int",
           "int",
           "int",
           "java.lang.String",
           "java.lang.String"
         });
     Assert.assertEquals(oldNum + 1, getInstancesNum(connection, name));
   } finally {
     if (connector != null) connector.close();
   }
 }
Esempio n. 6
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();
   }
 }
Esempio n. 7
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;
  }
  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;
  }
 // @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
   }
 }
Esempio n. 10
0
 public void run() {
   try {
     if (conn_ != null) {
       conn_.close();
     }
   } catch (Exception e) {
   }
 }
  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) {
      }
    }
  }
Esempio n. 12
0
 @Override
 protected void close() {
   if (connector != null) {
     try {
       connector.close();
     } catch (IOException ex) {
       Output.error("Exception while closing the JMX connector");
     }
   }
 }
Esempio n. 13
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();
  }
 @Override
 protected void tearDown() throws Exception {
   if (clientConnector != null) {
     try {
       clientConnector.close();
     } catch (Exception e) {
       // ignore
     }
     clientConnector = null;
   }
   super.tearDown();
 }
 public void closeRmiConnection() {
   if ((connector != null)) {
     try {
       hydra.Log.getLogWriter().info("Closing the RMI connector...");
       connector.close();
     } catch (Exception e) {
       hydra.Log.getLogWriter().warning(e);
     } finally {
       connector = null;
       mbs = null;
     }
   }
 }
Esempio n. 16
0
  public void disconnect()
      throws ListenerNotFoundException, InstanceNotFoundException, IOException {
    //        mbsc.removeNotificationListener(nodeAgent, this, null, null);

    nodeAgent = null;
    if (jmxc != null) {
      log.info("Closing jmx client connection ##################################################");
      jmxc.close();
    }
    if (mbsc != null) {
      mbsc = null;
    }
  }
  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;
  }
 public void stop() {
   try {
     if (adminMBean != null) {
       try {
         adminMBean.stop();
       } catch (InstanceNotFoundException e) {
         Logger myLogger = LoggerFactory.getLogger(Activator.class);
         myLogger.trace("Error stopping Admin MBean " + e.getMessage());
       }
     }
     if (connector != null) {
       connector.close();
     }
   } catch (Exception e) {
     // Ignore - could be because AMQ stopped.
   }
 }
Esempio n. 19
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);
    }
  }
  @Test
  public void testLocalAuthentication() throws Exception {
    log.info("testLocalAuthentication - Begin");
    config.saslMechanisms = Collections.singleton(JBOSS_LOCAL_USER);

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

    Map<String, Object> env = new HashMap<String, Object>(1);

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

    assertNotNull(connector.getConnectionId());

    connector.close();

    remotingServer.stop();
  }
  @Test
  public void testAnonymousAuthentication() throws Exception {
    log.info("testAnonymousAuthentication - Begin");
    JMXRemotingServer remotingServer = new JMXRemotingServer(config);
    remotingServer.start();

    Map<String, Object> env = new HashMap<String, Object>(0);

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

    assertNotNull(connector.getConnectionId());

    connector.close();

    remotingServer.stop();

    System.out.println("STOPPED");
  }
Esempio n. 22
0
  public static void main(String[] args) throws Exception {
    Server server = Server.builder().setHost("w2").setPort("1105").build();

    JMXConnector conn = null;
    try {
      conn = server.getServerConnection();
      MBeanServerConnection mbeanServer = conn.getMBeanServerConnection();

      TreeWalker3 tw = new TreeWalker3();
      tw.walkTree(mbeanServer, server);
    } catch (IOException e) {
      log.error(
          "Problem processing queries for server: " + server.getHost() + ":" + server.getPort(), e);
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
 @Override
 public void close() {
   if (!closed) {
     try {
       client.close();
       closed = true;
     } catch (IOException e) {
       throw new RuntimeException("Could not close connection", e);
     } finally {
       if (connector != null) {
         try {
           connector.close();
         } catch (IOException e) {
           throw new RuntimeException("Could not close JMX connection", e);
         }
       }
     }
   }
 }
 private synchronized void disconnectImpl(boolean sendClose) {
   // Close MBeanServer connection
   if (jmxc != null) {
     try {
       jmxc.removeConnectionNotificationListener(this);
       if (sendClose) jmxc.close();
     } catch (IOException e) {
       // Ignore...
     } catch (ListenerNotFoundException e) {
       LOGGER.log(Level.INFO, "disconnectImpl", e); // NOI18N
     }
     jmxc = null;
   }
   // Set connection state to DISCONNECTED
   if (!isDead) {
     isDead = true;
     setConnectionState(ConnectionState.DISCONNECTED);
   }
 }
Esempio n. 25
0
  @Override
  public void process(Exchange exchange) throws Exception {
    List<SimpleMeasurement> results = new ArrayList<SimpleMeasurement>();
    Message in = exchange.getIn();
    String serviceURL =
        (String)
            in.getHeader("jmxServiceUrl", "service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
    String user = (String) in.getHeader("jmxUser");
    String pass = (String) in.getHeader("jmxPassword");

    JMXConnector jmxConnector = connect(serviceURL, user, pass);

    ObjectName name = new ObjectName((String) in.getHeader("jmxObjectName"));
    String[] attributeNames = ((String) in.getHeader("jmxAttributeName", "")).split(",");
    String id = (String) in.getHeader("MeasurementID");
    double scale = Double.parseDouble((String) in.getHeader("Scale", "1"));

    Number value = null;
    try {
      MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();

      for (String attribute : attributeNames) {
        String[] parts = attribute.split("\\.");
        Object result = mBeanServerConnection.getAttribute(name, parts[0]);
        if (result instanceof Number) value = (Number) result;
        else if (result instanceof String) {
          String s = (String) result;
          value = Double.parseDouble(s.replace(',', '.'));
        } else if (result instanceof CompositeDataSupport) {
          CompositeDataSupport cds = (CompositeDataSupport) result;
          value = (Number) ((CompositeDataSupport) result).get(parts[1]);
        } else throw new IllegalArgumentException("Unknown type: " + result);
        results.add(
            new SimpleMeasurement(id + "." + attribute, value.doubleValue() / (double) scale));
      }
    } catch (Exception e) {
      LOGGER.error("An exception occurred:", e);
    } finally {
      jmxConnector.close();
    }
    exchange.getIn().setBody(results);
  }
 public void use() {
   JMXConnector jmxc = null;
   try {
     JMXServiceURL serviceURL = new JMXServiceURL(this.serviceUrl);
     jmxc = JMXConnectorFactory.connect(serviceURL, null);
     MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
     ObjectName mbeanName = new ObjectName(MBeanName);
     StatusMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, StatusMBean.class, true);
     System.out.println(mbeanProxy.getName());
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (jmxc != null) {
       try {
         jmxc.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
  public void runJmx() throws IOException {

    propEnv.put(JMXConnector.CREDENTIALS, credentials);

    try {

      serviceURL = new JMXServiceURL(urlString);
      jmxConnector = JMXConnectorFactory.connect(serviceURL, propEnv);
      MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
      ObjectName objectName = new ObjectName("jboss.as:management-root=server");
      String serverState = (String) connection.getAttribute(objectName, "serverState");
      System.out.println("server Status is:= " + serverState);

    } catch (MalformedURLException e) {

      e.printStackTrace();
    } catch (MalformedObjectNameException e) {

      e.printStackTrace();
    } catch (IOException e) {

      e.printStackTrace();
    } catch (AttributeNotFoundException e) {

      e.printStackTrace();
    } catch (InstanceNotFoundException e) {

      e.printStackTrace();
    } catch (MBeanException e) {

      e.printStackTrace();
    } catch (ReflectionException e) {

      e.printStackTrace();
    } finally {
      jmxConnector.close();
    }
  }
Esempio n. 28
0
  /**
   * @param args the command line arguments: must be -url <jmx-url>, or -port <port-number> [-host
   *     <host-or-ip], or -pid <pid>, or -help
   */
  public static void main(String[] args) throws Exception {
    // Parse arguments.
    final ConnectionArgs cArgs = new ConnectionArgs(args);

    // Get target's URL
    final JMXServiceURL target = cArgs.getJMXServiceURL();

    // Connect to target (assuming no security)
    final JMXConnector connector = JMXConnectorFactory.connect(target);

    // Get an MBeanServerConnection on the remote VM.
    final MBeanServerConnection remote = connector.getMBeanServerConnection();

    final RuntimeMXBean remoteRuntime =
        ManagementFactory.newPlatformMXBeanProxy(
            remote, ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);

    System.out.println("Target VM is: " + remoteRuntime.getName());
    System.out.println("Started since: " + remoteRuntime.getUptime());
    System.out.println("With Classpath: " + remoteRuntime.getClassPath());
    System.out.println("And args: " + remoteRuntime.getInputArguments());
    connector.close();
  }
  static int findVmid(String agentName) {
    MonitoredHost host;
    if (activeVms == null) {
      try {
        host = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));
        activeVms = host.activeVms();
      } catch (java.net.URISyntaxException e) {
        throw new InternalError(e.getMessage());
      } catch (sun.jvmstat.monitor.MonitorException e) {
        throw new InternalError(e.getMessage());
      }
    }

    for (Object vm : activeVms) {
      try {
        String address = ConnectorAddressLink.importFrom((Integer) vm);
        if (address == null) continue;
        JMXConnector jmxc;
        MBeanServerConnection server;
        JMXServiceURL jmxUrl = new JMXServiceURL(address);
        jmxc = JMXConnectorFactory.connect(jmxUrl);
        server = jmxc.getMBeanServerConnection();
        Object result;
        result = server.getAttribute(new ObjectName("net.multiverse:type=Engine"), "AgentName");
        jmxc.close();
        if (result != null && result.toString().equals(agentName)) return (Integer) vm;
      } catch (IOException e) {
        System.err.println("Unable to attach to " + (Integer) vm + ": " + e.getMessage());
      } catch (javax.management.InstanceNotFoundException e) {
        // ignore
      } catch (JMException e) {
        System.err.println("Unable to attach to " + (Integer) vm + ": " + e);
      }
    }

    return -1;
  }
Esempio n. 30
0
 public static void closeConnection() throws IOException {
   connector.close();
   connector = null;
 }