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:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Integration test for the registration service
 *///from  w ww  .j  a  v a 2 s  .  c o m
public void testRegistrationServiceListensForCacheChanges() throws Exception {
    ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);
    assertEquals(OBJECTS_IN_TEST_EHCACHE,
            mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());
    manager.addCache("new cache");
    assertEquals(43, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());
    manager.removeCache("sampleCache1");
    assertEquals(OBJECTS_IN_TEST_EHCACHE,
            mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());
    //        Thread.sleep(1000000);
}

From source file:com.taobao.tddl.common.util.TDDLMBeanServer.java

private void registerMBean0(Object o, String name) {
    // MBean//from   w w w.  jav a 2s.c  om
    if (null != mbs) {
        try {
            mbs.registerMBean(o, new ObjectName(o.getClass().getPackage().getName() + ":type="
                    + o.getClass().getSimpleName()
                    + (null == name ? (",id=" + o.hashCode()) : (",name=" + name + "-" + o.hashCode()))));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.streamsets.datacollector.http.JMXJsonServlet.java

/**
 * Process a GET request for the specified resource.
 *
 * @param request/*from   ww  w .j av  a  2  s  . co  m*/
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        JsonGenerator jg = null;
        String jsonpcb = null;
        PrintWriter writer = null;
        try {
            writer = response.getWriter();

            // "callback" parameter implies JSONP outpout
            jsonpcb = request.getParameter(CALLBACK_PARAM);
            if (jsonpcb != null) {
                response.setContentType("application/javascript; charset=utf8");
                writer.write(jsonpcb + "(");
            } else {
                response.setContentType("application/json; charset=utf8");
            }

            jg = jsonFactory.createGenerator(writer);
            jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
            jg.useDefaultPrettyPrinter();
            jg.writeStartObject();

            // query per mbean attribute
            String getmethod = request.getParameter("get");
            if (getmethod != null) {
                String[] splitStrings = getmethod.split("\\:\\:");
                if (splitStrings.length != 2) {
                    jg.writeStringField("result", "ERROR");
                    jg.writeStringField("message", "query format is not as expected.");
                    jg.flush();
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                listBeans(jg, new ObjectName(splitStrings[0]), splitStrings[1], response);
                return;
            }

            // query per mbean
            String qry = request.getParameter("qry");
            if (qry == null) {
                qry = "*:*";
            }
            listBeans(jg, new ObjectName(qry), null, response);
        } finally {
            if (jg != null) {
                jg.close();
            }
            if (jsonpcb != null) {
                writer.write(");");
            }
            if (writer != null) {
                writer.close();
            }
        }
    } catch (IOException e) {

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.brienwheeler.lib.jmx.logging.Log4jMBeanExporter.java

@SuppressWarnings("unchecked")
private synchronized void shutdown() {
    shutdown = true;/*from  w w  w  .  j  a va 2 s.  co m*/
    killDelayedThread();

    MBeanServer server = JmxUtils.locateMBeanServer();
    HierarchyDynamicMBean hdm = hierarchyDynamicMBean.get();
    for (ObjectName registeredName : registeredNames) {
        try {
            server.unregisterMBean(registeredName);

            // The AbstractDynamicMBean base class of the HierarchyDynamicMBean tracks these names too
            // and will later try to unregister them and throw warning log messages unless we violate its
            // privacy and clean out its internal bookkeeping
            Field fld = ReflectionUtils.findField(hdm.getClass(), "mbeanList", Vector.class);
            fld.setAccessible(true);
            Vector<ObjectName> mbeanList = (Vector<ObjectName>) ReflectionUtils.getField(fld, hdm);
            mbeanList.remove(registeredName);
        } catch (Exception e) {
            log.error("Error unregistering " + registeredName.getCanonicalName(), e);
        }
    }
    registeredNames.clear();

    if (registeredHierarchy) {
        try {
            ObjectName mbo = new ObjectName(LOG4J_HIERARCHY_DEFAULT);
            server.unregisterMBean(mbo);
        } catch (Exception e) {
            log.error("Error unregistering Log4j MBean Hierarchy", e);
        }
        registeredHierarchy = false;
    }
}

From source file:org.red5.server.scheduling.ApplicationSchedulingService.java

protected void unregisterJMX() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {//  www  . j  av a  2  s  .co  m
        ObjectName oName = null;
        if (instanceId == null) {
            oName = new ObjectName(
                    "org.red5.server:type=ApplicationSchedulingService,applicationName=" + applicationName);
        } else {
            oName = new ObjectName("org.red5.server:type=ApplicationSchedulingService,applicationName="
                    + applicationName + ",instanceId=" + instanceId);
        }
        mbs.unregisterMBean(oName);
    } catch (Exception e) {
        log.warn("Exception unregistering", e);
    }
}

From source file:org.ff4j.jmx.FF4JMBeanTest.java

@Test
public void should_disable_feature() throws Exception {
    ObjectName objectName = new ObjectName(FF4J_OBJECT_NAME);
    mbServConn.invoke(objectName, "disableFeature", new Object[] { "jmxEnabledFeature" },
            new String[] { "java.lang.String" });
    assertFF4J.assertThatFeatureIsDisabled("jmxEnabledFeature");
}

From source file:org.taverna.server.master.interaction.InteractionFeedSupport.java

@PostConstruct
void determinePorts() {
    try {/*from ww  w. j  a  v a  2 s  .  c  om*/
        MBeanServer mbs = getPlatformMBeanServer();
        for (ObjectName obj : mbs.queryNames(new ObjectName("*:type=Connector,*"),
                match(attr("protocol"), value("HTTP/1.1")))) {
            String scheme = mbs.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            endPoints.put(scheme, new URL(scheme + "://localhost:" + port));
        }
        getLog(getClass()).info("installed feed port publication mapping for " + endPoints.keySet());
    } catch (Exception e) {
        getLog(getClass()).error("failure in determining local port mapping", e);
    }
}

From source file:ddf.catalog.cache.solr.impl.SolrCache.java

/**
 * Convenience constructor that creates a the Solr server
 *
 * @param adapter injected implementation of FilterAdapter
 *//*from  ww  w  .  jav a  2  s. c o  m*/
public SolrCache(FilterAdapter adapter, SolrFilterDelegateFactory solrFilterDelegateFactory) {
    this.filterAdapter = adapter;
    this.solrFilterDelegateFactory = solrFilterDelegateFactory;
    this.url = SystemBaseUrl.constructUrl("/solr");
    this.updateServer(this.url);
    configureCacheExpirationScheduler();

    try {
        objectName = new ObjectName(SolrCacheMBean.OBJECTNAME);
    } catch (MalformedObjectNameException e) {
        LOGGER.info("Could not create object name", e);
    }

    configureMBean();
}

From source file:fr.xebia.management.statistics.ProfileAspectTest.java

@Test
public void testProfiledAnnotationWithDefaultName() throws Exception {

    // test/*from   ww  w .  java2  s. c o  m*/
    testService.doJobWithDefaultName();

    // verify

    // don't use getClass().getName() because the class is enhanced by CGLib
    // and its name looks like
    // "...ProfileAspectTest$TestService$$EnhancerByCGLIB$$9b64fd54"
    String name = "f.x.m.s.ProfileAspectTest$TestService.doJobWithDefaultName";
    ServiceStatistics serviceStatistics = profileAspect.serviceStatisticsByName.get(name);
    System.out.println(profileAspect.serviceStatisticsByName);
    assertNotNull(serviceStatistics);
    assertEquals(1, serviceStatistics.getInvocationCount());
    assertEquals(0, serviceStatistics.getSlowInvocationCount());
    assertEquals(0, serviceStatistics.getVerySlowInvocationCount());
    assertEquals(0, serviceStatistics.getBusinessExceptionCount());
    assertEquals(0, serviceStatistics.getServiceUnavailableExceptionCount());
    assertEquals(0, serviceStatistics.getCommunicationExceptionCount());
    assertEquals(0, serviceStatistics.getOtherExceptionCount());
    assertEquals(0, serviceStatistics.getTotalExceptionCount());

    Set<ObjectInstance> mbeansInstances = mbeanServer
            .queryMBeans(new ObjectName("com.mycompany:type=ServiceStatistics,name=" + name), null);
    assertEquals(1, mbeansInstances.size());

    ObjectName serviceStatisticsObjectName = mbeansInstances.iterator().next().getObjectName();
    assertEquals(1, mbeanServer.getAttribute(serviceStatisticsObjectName, "InvocationCount"));

}

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

public void initializePlugin(PluginManager manager, File pluginDirectory) {
    /*//from w  w  w  .j a  v  a 2s  . c o  m
      Initialize properties so that all the properties added by the plugin schema upgrade are loaded
     */
    JiveProperties.getInstance().init();
    //log the java version
    String version = System.getProperty("java.version");
    String vendor = System.getProperty("java.vendor");
    String vmName = System.getProperty("java.vm.name");
    Log.warn("Java details vendor:{} version:{} vmName:{}", vendor, version, vmName);

    {
        try {
            JiveGlobals.setProperty(MMXConfigKeys.MMX_VERSION, MMXVersion.getVersion());
            Log.debug("mmx properties updated");
        } catch (Exception e) {
            Log.error("Problem in reading java properties", e);
        }
    }

    Log.info("MMX version:" + MMXVersion.getVersion());

    /**
     * register the config MBean
     */
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mbeanName = new ObjectName(MMXServerConstants.MMX_MBEAN_NAME);
        MMXManagedConfigurationMBean mbean = new MMXManagedConfiguration(MMXConfiguration.getConfiguration());
        mbs.registerMBean(mbean, mbeanName);
    } catch (Throwable t) {
        Log.warn("Configuration MBean registration failed", t);
    }

    // Add Context event dispatcher
    try {
        Class.forName(GeoEventDispatcher.class.getName());
        contextDispatcher = ContextDispatcherFactory.getInstance()
                .getDispatcher((GeoEventDispatcher.class.getName()));
    } catch (IllegalAccessException e) {
        Log.error("event dispatcher error", e);
    } catch (InstantiationException e) {
        Log.error("event dispatcher error", e);
    } catch (ClassNotFoundException e) {
        Log.error("event dispatcher error", e);
    }

    XMPPServer server = XMPPServer.getInstance();
    IQRouter iqRouter = server.getIQRouter();

    // Add IQHandler to register an application for push notification and
    // generate a pair of app-key and api-key for the client app.
    mIQAppRegHandler = new AppHandler("appreg");
    mIQDevRegHandler = new DeviceHandler("devreg");
    mIQUserRegHandler = new MMXUserHandler("userreg");
    mIQMessageStateHandler = new MessageStateHandler("msgstate");
    mIQPubSubHandler = new MMXPubSubHandler("pubsub");

    mIQWakeupNSHandler = new MMXWakeupNSHandler("wakeupns");
    mIQPushNSHandler = new MMXPushNSHandler("pushns");
    mIQMsgAckNSHandler = new MsgAckIQHandler("msgack");

    mmxPacketInterceptor = new MMXPacketInterceptor(new MMXMessageHandlingRule());

    iqRouter.addHandler(mIQAppRegHandler);
    iqRouter.addHandler(mIQDevRegHandler);
    iqRouter.addHandler(mIQUserRegHandler);
    iqRouter.addHandler(mIQMessageStateHandler);
    iqRouter.addHandler(mIQPubSubHandler);
    iqRouter.addHandler(mIQWakeupNSHandler);
    iqRouter.addHandler(mIQPushNSHandler);
    iqRouter.addHandler(mIQMsgAckNSHandler);

    Log.info("App Management Plugin is initialized");

    InterceptorManager im = InterceptorManager.getInstance();
    im.addInterceptor(mmxPacketInterceptor);
    Log.info("MMXPacketInterceptor is initialized");

    if (ClusterManager.isClusteringEnabled()) {
        Log.debug("initializePlugin : clustering is available, timer tasks will start on joining cluster");
        ClusterManager.addListener(this);
    } else {
        Log.debug("initializePlugin : Clustering is disabled, starting scheduled tasks");
        startSchedulededTasks();
    }

    publicAPIServer = new MMXPublicAPIServer();
    publicAPIServer.start();

    //initialize the APNS connection pool.
    initializeAPNSConnectionPool();

    adminAPIServer = new MMXAdminAPIServer();
    adminAPIServer.start();

}