Example usage for javax.management ObjectName ObjectName

List of usage examples for javax.management ObjectName ObjectName

Introduction

In this page you can find the example usage for javax.management ObjectName ObjectName.

Prototype

public ObjectName(String name) throws MalformedObjectNameException 

Source Link

Document

Construct an object name from the given string.

Usage

From source file:com.tesora.dve.server.bootstrap.BootstrapHost.java

@Override
protected void unregisterMBeans() {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    try {//  w  w w.  ja  v  a2  s.  co m
        server.unregisterMBean(new ObjectName(MBEAN_BOOTSTRAP_HOST));
    } catch (Exception e) {
        logger.error("Unable to unregister " + MBEAN_BOOTSTRAP_HOST + " mBean", e);
    }

    try {
        server.unregisterMBean(new ObjectName(MBEAN_LOG4J_HIERARCHY));
    } catch (Exception e) {
        logger.error("Unable to unregister " + MBEAN_LOG4J_HIERARCHY + " mBean", e);
    }

    super.unregisterMBeans();
}

From source file:au.com.redboxresearchdata.fascinator.plugins.JsonHarvestQueueConsumer.java

public void run() {
    try {//from ww  w.j  a v  a  2 s .  com
        // Get a connection to the broker
        String brokerUrl = globalConfig.getString(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL,
                "messaging", "url");
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
        connection = connectionFactory.createConnection();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        consumer = session.createConsumer(session.createQueue(QUEUE_ID));
        consumer.setMessageListener(this);

        producer = session.createProducer(session.createTopic(EVENT_TOPIC_ID));
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        connection.start();

        toolChainEntry = globalConfig.getString(DEFAULT_TOOL_CHAIN_QUEUE, "messaging", "toolChainQueue");

        failedJsonMap = new HashMap<String, HarvestItem>();
        failedJsonList = new ArrayList<String>();
        harvestRequests = new HashMap<String, HarvestRequest>();
        // registering managed bean...
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName(
                "au.com.redboxresearchdata.fascinator.plugins:type=JsonHarvestQueue");
        mbs.registerMBean(this, mxbeanName);
        log.info("'{}' is running...", name);
    } catch (JMSException ex) {
        log.error("Error starting message thread!", ex);
    } catch (MalformedObjectNameException e) {
        log.error("Error configuring MBean, invalid name", e);
    } catch (InstanceAlreadyExistsException e) {
        log.error("Error configuring MBean, instance exists.", e);
    } catch (MBeanRegistrationException e) {
        log.error("Error registering MBean. ", e);
    } catch (NotCompliantMBeanException e) {
        log.error("Error configuring Mbean, non-compliant!", e);
    }
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Integration test for the registration service
 *///  w  w w.  j  av  a  2s  .co  m
public void testRegistrationServiceTwoTrue() throws Exception {
    ManagementService.registerMBeans(manager, mBeanServer, true, true, false, false);
    assertEquals(14, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

@After
public void teardown() throws Exception {
    ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME);
    server.unregisterMBean(name);/*from www .  j a v a  2  s .  com*/
    jmxConnectorServer.stop();
    restoreDefaults();
}

From source file:io.github.albertopires.mjc.JConsoleM.java

public Long getNonHeapUsage() throws Exception {
    ObjectName mbeanName;//  w  w w  .  j a  va2 s.  com
    mbeanName = new ObjectName("java.lang:type=Memory");
    CompositeDataSupport o;
    o = (CompositeDataSupport) mbsc.getAttribute(mbeanName, "NonHeapMemoryUsage");
    return Long.valueOf(o.get("used").toString());
}

From source file:com.betfair.cougar.transport.jetty.JettyServerWrapper.java

public void initialiseConnectors() throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);
    threadPool.setName("JettyThread");
    jettyServer = new Server(threadPool);

    jettyServer.setStopAtShutdown(true);

    MBeanContainer container = new MBeanContainer(mbeanServer);
    jettyServer.addBean(container);/*  ww  w . j  a  v  a 2  s . c  o m*/

    LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(jettyServer);
    lowResourcesMonitor.setPeriod(lowResourcesPeriod);
    lowResourcesMonitor.setLowResourcesIdleTimeout(lowResourcesIdleTime);
    lowResourcesMonitor.setMonitorThreads(lowResourcesMonitorThreads);
    lowResourcesMonitor.setMaxConnections(lowResourcesMaxConnections);
    lowResourcesMonitor.setMaxMemory(lowResourcesMaxMemory);
    lowResourcesMonitor.setMaxLowResourcesTime(lowResourcesMaxTime);
    jettyServer.addBean(lowResourcesMonitor);

    // US24803 - Needed for preventing Hashtable key collision DoS CVE-2012-2739
    jettyServer.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);

    List<Connector> connectors = new ArrayList<Connector>();

    if (httpPort != -1) {
        httpConfiguration = createHttpConfiguration();
        setBufferSizes(httpConfiguration);
        if (httpForwarded) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConnector = createHttpConnector(jettyServer, httpConfiguration, httpAcceptors, httpSelectors);
        httpConnector.setPort(httpPort);
        httpConnector.setReuseAddress(httpReuseAddress);
        httpConnector.setIdleTimeout(httpMaxIdle);
        httpConnector.setAcceptQueueSize(httpAcceptQueueSize);
        httpConnector.addBean(new ConnectorStatistics());

        connectors.add(httpConnector);
    }

    if (httpsPort != -1) {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(httpsKeystore.getFile().getCanonicalPath());
        sslContextFactory.setKeyStoreType(httpsKeystoreType);
        sslContextFactory.setKeyStorePassword(httpsKeyPassword);
        if (StringUtils.isNotBlank(httpsCertAlias)) {
            sslContextFactory.setCertAlias(httpsCertAlias);
        }
        sslContextFactory.setKeyManagerPassword(httpsKeyPassword);
        // if you need it then you defo want it
        sslContextFactory.setWantClientAuth(httpsNeedClientAuth || httpsWantClientAuth);
        sslContextFactory.setNeedClientAuth(httpsNeedClientAuth);
        sslContextFactory.setRenegotiationAllowed(httpsAllowRenegotiate);

        httpsConfiguration = createHttpConfiguration();
        setBufferSizes(httpsConfiguration);
        if (httpsForwarded) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }

        httpsConnector = createHttpsConnector(jettyServer, httpsConfiguration, httpsAcceptors, httpsSelectors,
                sslContextFactory);
        httpsConnector.setPort(httpsPort);
        httpsConnector.setReuseAddress(httpsReuseAddress);
        httpsConnector.setIdleTimeout(httpsMaxIdle);
        httpsConnector.setAcceptQueueSize(httpsAcceptQueueSize);
        httpsConnector.addBean(new ConnectorStatistics());

        mbeanServer.registerMBean(getKeystoreCertificateChains(), new ObjectName("CoUGAR.https:name=keyStore"));
        // truststore is not required if we don't want client auth
        if (httpsWantClientAuth) {
            sslContextFactory.setTrustStorePath(httpsTruststore.getFile().getCanonicalPath());
            sslContextFactory.setTrustStoreType(httpsTruststoreType);
            sslContextFactory.setTrustStorePassword(httpsTrustPassword);
            mbeanServer.registerMBean(getTruststoreCertificateChains(),
                    new ObjectName("CoUGAR.https:name=trustStore"));
        }
        connectors.add(httpsConnector);
    }

    if (connectors.size() == 0) {
        throw new IllegalStateException(
                "HTTP transport requires at least one port enabled to function correctly.");
    }

    jettyServer.setConnectors(connectors.toArray(new Connector[connectors.size()]));
}

From source file:de.unioninvestment.eai.portal.portlet.crud.domain.model.JolokiaMBeanServerConnectionTest.java

@Test
public void shouldQueryNames() throws IOException, AttributeNotFoundException, InstanceNotFoundException,
        MBeanException, ReflectionException, J4pException, MalformedObjectNameException, ParseException {

    ObjectName objectName = new ObjectName(TEST_OBJECT_NAME_NAMES);

    JolokiaMBeanServerConnection jolokiaMBeanServerConnection = new JolokiaMBeanServerConnection();
    jolokiaMBeanServerConnection.setJ4pClient(j4pClientMock);

    J4pReadRequest request = new J4pReadRequest(objectName);
    J4pResponse<J4pReadRequest> response = new J4pResponse<J4pReadRequest>(request,
            (JSONObject) new JSONParser().parse(TEST_RESPONSE_NAMES)) {
    };/*from w  w  w  .  ja va2s.c o m*/

    when(j4pClientMock.execute(any(J4pReadRequest.class))).thenReturn(response);

    Set<ObjectName> result = jolokiaMBeanServerConnection.queryNames(objectName, null);

    assertTrue(result.size() == 1);
    assertTrue(result.contains(new ObjectName("org.apache.servicemix:ContainerName=ServiceMix,"
            + "Name=algo-benchmark-targetadapter-sa,Type=ServiceAssembly")));
}

From source file:com.googlecode.jmxtrans.model.Query.java

private Query(String obj, List<String> keys, List<String> attr, Set<String> typeNames, String resultAlias,
        boolean useObjDomainAsKey, boolean allowDottedKeys, boolean useAllTypeNames,
        List<OutputWriterFactory> outputWriterFactories, List<OutputWriter> outputWriters) {
    try {//w  w  w  .  java2s  .  c om
        this.objectName = new ObjectName(obj);
    } catch (MalformedObjectNameException e) {
        throw new IllegalArgumentException("Invalid object name: " + obj, e);
    }
    this.attr = copyOf(firstNonNull(attr, Collections.<String>emptyList()));
    this.resultAlias = resultAlias;
    this.useObjDomainAsKey = firstNonNull(useObjDomainAsKey, false);
    this.keys = copyOf(firstNonNull(keys, Collections.<String>emptyList()));
    this.allowDottedKeys = allowDottedKeys;
    this.useAllTypeNames = useAllTypeNames;
    this.outputWriters = copyOf(firstNonNull(outputWriterFactories, ImmutableList.<OutputWriterFactory>of()));
    // We need to preserve the order of typeNames. So note that copyOf
    // does not mess with the order. 
    this.typeNames = ImmutableSet.copyOf(firstNonNull(typeNames, Collections.<String>emptySet()));

    this.typeNameValuesStringBuilder = makeTypeNameValuesStringBuilder();

    this.outputWriterInstances = copyOf(firstNonNull(outputWriters, ImmutableList.<OutputWriter>of()));
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Integration test for the registration service
 *//*from  w  w  w .  j  a v a  2 s  .  c  om*/
public void testRegistrationServiceOneTrue() throws Exception {
    ManagementService.registerMBeans(manager, mBeanServer, true, false, false, false);
    assertEquals(1, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

}

From source file:com.enioka.jqm.tools.JqmEngine.java

/**
 * Starts the engine/*  w  ww . j  a va2s  .c  o  m*/
 * 
 * @param nodeName
 *            the name of the node to start, as in the NODE table of the database.
 * @throws JqmInitError
 */
void start(String nodeName) {
    if (nodeName == null || nodeName.isEmpty()) {
        throw new IllegalArgumentException("nodeName cannot be null or empty");
    }

    // Set thread name - used in audits
    Thread.currentThread().setName("JQM engine;;" + nodeName);
    Helpers.setLogFileName(nodeName);

    // Log: we are starting...
    jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting");
    jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by "
            + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version "
            + System.getProperty("java.vm.version"));

    // JNDI first - the engine itself uses JNDI to fetch its connections!
    Helpers.registerJndiIfNeeded();

    // Database connection
    EntityManager em = Helpers.getNewEm();

    // Node configuration is in the database
    node = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    // Check if double-start
    long toWait = (long) (1.1 * Long.parseLong(Helpers.getParameter("internalPollingPeriodMs", "60000", em)));
    if (node.getLastSeenAlive() != null
            && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) {
        long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis();
        throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000
                + " seconds ago. Either stop the other node, or if it already stopped, please wait "
                + (toWait - r) / 1000 + " seconds");
    }

    // Prevent very quick multiple starts by immediately setting the keep-alive
    em.getTransaction().begin();
    node.setLastSeenAlive(Calendar.getInstance());
    em.getTransaction().commit();

    // Only start if the node configuration seems OK
    Helpers.checkConfiguration(nodeName, em);

    // Log parameters
    Helpers.dumpParameters(em, node);

    // Log level
    Helpers.setLogLevel(node.getRootLogLevel());

    // Log multicasting (& log4j stdout redirect)
    GlobalParameter gp1 = em
            .createQuery("SELECT g FROM GlobalParameter g WHERE g.key = :k", GlobalParameter.class)
            .setParameter("k", "logFilePerLaunch").getSingleResult();
    if ("true".equals(gp1.getValue()) || "both".equals(gp1.getValue())) {
        RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger().getAppender("rollingfile");
        MultiplexPrintStream s = new MultiplexPrintStream(System.out, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setOut(s);
        ((ConsoleAppender) Logger.getRootLogger().getAppender("consoleAppender"))
                .setWriter(new OutputStreamWriter(s));
        s = new MultiplexPrintStream(System.err, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setErr(s);
    }

    // Remote JMX server
    if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0
            && node.getJmxServerPort() > 0) {
        JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns());
    } else {
        jqmlogger.info(
                "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined");
    }

    // Jetty
    this.server = new JettyServer();
    this.server.start(node, em);

    // JMX
    if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName());
            mbs.registerMBean(this, name);
        } catch (Exception e) {
            throw new JqmInitError("Could not create JMX beans", e);
        }
        jqmlogger.info("JMX management bean for the engine was registered");
    } else {
        loadJmxBeans = false;
        jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero");
    }

    // Security
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManagerPayload());
    }
    jqmlogger.info("Security manager was registered");

    // Cleanup
    purgeDeadJobInstances(em, this.node);

    // Force Message EMF load
    em.createQuery("SELECT m FROM Message m WHERE 1=0", Message.class).getResultList();

    // Pollers
    syncPollers(em, this.node);
    jqmlogger.info("All required queues are now polled");

    // Internal poller (stop notifications, keepalive)
    intPoller = new InternalPoller(this);
    Thread t = new Thread(intPoller);
    t.start();

    // Kill notifications
    killHook = new SignalHandler(this);
    Runtime.getRuntime().addShutdownHook(killHook);

    // Done
    em.close();
    em = null;
    latestNodeStartedName = node.getName();
    jqmlogger.info("End of JQM engine initialization");
}