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.sun.grizzly.http.jk.common.ChannelUn.java

public void registerRequest(Request req, MsgContext ep, int count) {
    if (this.domain != null) {
        try {//from   w ww .j  av  a2  s  . c  o  m

            RequestInfo rp = req.getRequestProcessor();
            rp.setGlobalProcessor(global);
            ObjectName roname = new ObjectName(getDomain() + ":type=RequestProcessor,worker=" + getChannelName()
                    + ",name=JkRequest" + count);
            ep.setNote(JMXRequestNote, roname);

            Registry.getRegistry(null, null).registerComponent(rp, roname, null);
        } catch (Exception ex) {
            LoggerUtils.getLogger().log(Level.WARNING, "Error registering request");
        }
    }
}

From source file:com.bigdata.dastor.service.StorageService.java

public StorageService() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {/*w ww .  j  av a 2s. com*/
        mbs.registerMBean(this, new ObjectName("com.bigdata.dastor.service:type=StorageService"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    bootstrapSet = Multimaps.synchronizedSetMultimap(HashMultimap.<InetAddress, String>create());

    /* register the verb handlers */
    MessagingService.instance.registerVerbHandlers(Verb.BINARY, new BinaryVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.MUTATION, new RowMutationVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.READ_REPAIR, new ReadRepairVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.READ, new ReadVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.RANGE_SLICE, new RangeSliceVerbHandler());
    // see BootStrapper for a summary of how the bootstrap verbs interact
    MessagingService.instance.registerVerbHandlers(Verb.BOOTSTRAP_TOKEN,
            new BootStrapper.BootstrapTokenVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_REQUEST, new StreamRequestVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_INITIATE, new StreamInitiateVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_INITIATE_DONE,
            new StreamInitiateDoneVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_FINISHED, new StreamFinishedVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.READ_RESPONSE, new ResponseVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.TREE_REQUEST, new TreeRequestVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.TREE_RESPONSE,
            new AntiEntropyService.TreeResponseVerbHandler());

    MessagingService.instance.registerVerbHandlers(Verb.JOIN, new GossiperJoinVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_SYN, new GossipDigestSynVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK, new GossipDigestAckVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK2, new GossipDigestAck2VerbHandler());

    replicationStrategies = new HashMap<String, AbstractReplicationStrategy>();
    for (String table : DatabaseDescriptor.getNonSystemTables()) {
        AbstractReplicationStrategy strat = getReplicationStrategy(tokenMetadata_, table);
        replicationStrategies.put(table, strat);
    }
    replicationStrategies = Collections.unmodifiableMap(replicationStrategies);

    // spin up the streaming serivice so it is available for jmx tools.
    if (StreamingService.instance == null)
        throw new RuntimeException("Streaming service is unavailable.");
}

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

public long getCMSUsage(ServerConfiguration serverConfiguration) throws Exception {
    ObjectName mbeanName = null;//  www . j av  a2  s  .  co  m
    if (serverConfiguration.getJdkVersion().equals(JdkVersion.JDK6)) {
        mbeanName = new ObjectName("java.lang:type=MemoryPool,name=CMS Old Gen");
        CompositeDataSupport o;
        o = (CompositeDataSupport) mbsc.getAttribute(mbeanName, "Usage");
        return ((Long) o.get("used")).longValue();
    } else {
        return 0L;
    }
}

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

@Around(value = "execution(* *(..)) && @annotation(profiled)", argNames = "pjp,profiled")
public Object profileInvocation(ProceedingJoinPoint pjp, Profiled profiled) throws Throwable {

    logger.trace("> profileInvocation({},{}", pjp, profiled);

    MethodSignature jointPointSignature = (MethodSignature) pjp.getStaticPart().getSignature();

    // COMPUTE SERVICE STATISTICS NAME
    Expression nameAsExpression = profiledMethodNameAsExpressionByMethod.get(jointPointSignature.getMethod());
    if (nameAsExpression == null) {
        if (StringUtils.hasLength(profiled.name())) {
            String nameAsStringExpression = profiled.name();
            nameAsExpression = expressionParser.parseExpression(nameAsStringExpression, parserContext);
        } else {//from  w  w w  . j a  v  a 2s  .c o  m
            String fullyQualifiedMethodName = getFullyQualifiedMethodName(//
                    jointPointSignature.getDeclaringTypeName(), //
                    jointPointSignature.getName(), //
                    this.classNameStyle);
            nameAsExpression = new LiteralExpression(fullyQualifiedMethodName);
        }
    }

    String serviceStatisticsName;
    if (nameAsExpression instanceof LiteralExpression) {
        // Optimization : prevent useless objects instantiations
        serviceStatisticsName = nameAsExpression.getExpressionString();
    } else {
        serviceStatisticsName = nameAsExpression.getValue(new RootObject(pjp), String.class);
    }

    // LOOKUP SERVICE STATISTICS
    ServiceStatistics serviceStatistics = serviceStatisticsByName.get(serviceStatisticsName);

    if (serviceStatistics == null) {
        // INSTIANCIATE NEW SERVICE STATISTICS
        ServiceStatistics newServiceStatistics = new ServiceStatistics(//
                new ObjectName(this.jmxDomain + ":type=ServiceStatistics,name=" + serviceStatisticsName), //
                profiled.businessExceptionsTypes(), profiled.communicationExceptionsTypes());

        newServiceStatistics.setSlowInvocationThresholdInMillis(profiled.slowInvocationThresholdInMillis());
        newServiceStatistics
                .setVerySlowInvocationThresholdInMillis(profiled.verySlowInvocationThresholdInMillis());
        int maxActive;
        if (StringUtils.hasLength(profiled.maxActiveExpression())) {
            maxActive = expressionParser.parseExpression(profiled.maxActiveExpression(), parserContext)
                    .getValue(new RootObject(pjp), Integer.class);
        } else {
            maxActive = profiled.maxActive();
        }
        newServiceStatistics.setMaxActive(maxActive);
        newServiceStatistics.setMaxActiveSemaphoreAcquisitionMaxTimeInNanos(TimeUnit.NANOSECONDS
                .convert(profiled.maxActiveSemaphoreAcquisitionMaxTimeInMillis(), TimeUnit.MILLISECONDS));

        ServiceStatistics previousServiceStatistics = serviceStatisticsByName.putIfAbsent(serviceStatisticsName,
                newServiceStatistics);
        if (previousServiceStatistics == null) {
            serviceStatistics = newServiceStatistics;
            mbeanExporter.registerManagedResource(serviceStatistics);
        } else {
            serviceStatistics = previousServiceStatistics;
        }
    }

    // INVOKE AND PROFILE INVOCATION
    long nanosBefore = System.nanoTime();

    Semaphore semaphore = serviceStatistics.getMaxActiveSemaphore();
    if (semaphore != null) {
        boolean acquired = semaphore.tryAcquire(
                serviceStatistics.getMaxActiveSemaphoreAcquisitionMaxTimeInNanos(), TimeUnit.NANOSECONDS);
        if (!acquired) {
            serviceStatistics.incrementServiceUnavailableExceptionCount();
            throw new ServiceUnavailableException("Service '" + serviceStatisticsName + "' is unavailable: "
                    + serviceStatistics.getCurrentActive() + " invocations of are currently running");
        }
    }
    serviceStatistics.incrementCurrentActiveCount();
    try {

        Object returned = pjp.proceed();

        return returned;
    } catch (Throwable t) {
        serviceStatistics.incrementExceptionCount(t);
        throw t;
    } finally {
        if (semaphore != null) {
            semaphore.release();
        }
        serviceStatistics.decrementCurrentActiveCount();
        long deltaInNanos = System.nanoTime() - nanosBefore;
        serviceStatistics.incrementInvocationCounterAndTotalDurationWithNanos(deltaInNanos);
        if (logger.isDebugEnabled()) {
            logger.debug("< profileInvocation({}): {}ns", serviceStatisticsName, deltaInNanos);
        }
    }
}

From source file:fr.xebia.springframework.concurrent.ThreadPoolExecutorFactory.java

@Override
protected ThreadPoolExecutor createInstance() throws Exception {
    Assert.isTrue(this.corePoolSize >= 0, "corePoolSize must be greater than or equal to zero");
    Assert.isTrue(this.maximumPoolSize > 0, "maximumPoolSize must be greater than zero");
    Assert.isTrue(this.maximumPoolSize >= this.corePoolSize,
            "maximumPoolSize must be greater than or equal to corePoolSize");
    Assert.isTrue(this.queueCapacity >= 0, "queueCapacity must be greater than or equal to zero");

    CustomizableThreadFactory threadFactory = new CustomizableThreadFactory(this.beanName + "-");
    threadFactory.setDaemon(true);/*from w  w  w .j a  v  a 2 s  .  co  m*/

    BlockingQueue<Runnable> blockingQueue;
    if (queueCapacity == 0) {
        blockingQueue = new SynchronousQueue<Runnable>();
    } else {
        blockingQueue = new LinkedBlockingQueue<Runnable>(queueCapacity);
    }
    ThreadPoolExecutor instance = new SpringJmxEnabledThreadPoolExecutor(corePoolSize, //
            maximumPoolSize, //
            keepAliveTimeInSeconds, //
            TimeUnit.SECONDS, //
            blockingQueue, //
            threadFactory, //
            rejectedExecutionHandlerClass.newInstance(), //
            new ObjectName("java.util.concurrent:type=ThreadPoolExecutor,name=" + beanName));

    return instance;
}

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

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

    final ByteArrayInputStream bis = new ByteArrayInputStream(TEST_RESPONSE_REMOTE_SCRIPTING.getBytes());

    when(httpClientMock.execute(any(HttpUriRequest.class))).thenReturn(httpResponseMock);
    when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);
    when(httpEntityMock.getContent()).thenReturn(bis);

    JolokiaMBeanServerConnection jolokiaMBeanServerConnection = new JolokiaMBeanServerConnection();
    jolokiaMBeanServerConnection.setJ4pClient(new J4pClient(TEST_URL, httpClientMock));
    ObjectName objectName = new ObjectName(REMOTE_SCRIPTING_MBEAN_NAME);

    assertTrue(jolokiaMBeanServerConnection.isRegistered(objectName));
}

From source file:net.sbbi.upnp.jmx.upnp.UPNPConnectorServer.java

public void start() throws IOException {
    MBeanServer server = getMBeanServer();
    if (exposeMBeansAsUPNP.booleanValue()) {
        try {//  ww  w .  j a v  a2s.c  o m
            ObjectName delegate = new ObjectName("JMImplementation:type=MBeanServerDelegate");
            NotificationEmitter emmiter = (NotificationEmitter) MBeanServerInvocationHandler
                    .newProxyInstance(server, delegate, NotificationEmitter.class, false);
            // register for MBeans registration
            emmiter.addNotificationListener(this, null, this);
        } catch (Exception ex) {
            IOException ioEx = new IOException("UPNPConnector start error");
            ioEx.initCause(ex);
            throw ioEx;
        }
    }
    if (exposeUPNPAsMBeans.booleanValue()) {
        int timeout = 2500;
        if (env.containsKey(EXPOSE_UPNP_DEVICES_AS_MBEANS_TIMEOUT)) {
            timeout = ((Integer) env.get(EXPOSE_UPNP_DEVICES_AS_MBEANS_TIMEOUT)).intValue();
        }
        try {
            discoveryBeanName = new ObjectName("UPNPLib discovery:name=Discovery MBean_" + this.hashCode());
            UPNPDiscoveryMBean bean = new UPNPDiscovery(timeout, handleSSDPMessages.booleanValue(), true);
            server.registerMBean(bean, discoveryBeanName);
        } catch (Exception ex) {
            IOException ioEx = new IOException("Error occured during MBeans discovery");
            ioEx.initCause(ex);
            throw ioEx;
        }
    }
    if (exposeExistingMBeansAsUPNP.booleanValue()) {
        int c = 0;
        Set objectInstances = super.getMBeanServer().queryNames(null, null);
        for (Iterator i = objectInstances.iterator(); i.hasNext();) {
            ObjectName name = (ObjectName) i.next();
            MBeanServerNotification not = new MBeanServerNotification(
                    MBeanServerNotification.REGISTRATION_NOTIFICATION, this, c++, name);
            handleNotification(not, this);
        }
    }
}

From source file:com.athena.dolly.console.module.jmx.JmxClientManager.java

public static HashMap<String, Object> getCacheStatisticsInfo(String nodeName) {
    try {/*from ww w. j a  va 2 s .c  o m*/
        ObjectName cacheStatisticsInfo = new ObjectName(
                "jboss.infinispan:type=Cache,name=\"default(dist_sync)\",manager=\"clustered\",component=Statistics");
        HashMap<String, Object> cacheMap = getObjectNameInfo(cacheStatisticsInfo, nodeName);
        return cacheMap;
    } catch (Exception e) {
        logger.error("unhandled exception has errored : ", e);
    }

    return null;
}

From source file:com.betfair.cougar.core.impl.jmx.HtmlAdaptorParser.java

private void runOperation(StringBuilder buf, String son, String operation, String separator) {
    try {//from  w  ww.j a v a2  s  . com
        ObjectName on = new ObjectName(son);
        Object result = mbs.invoke(on, operation, new Object[0], new String[0]);
        buf.append(on.toString()).append(separator).append(operation).append(separator).append(result)
                .append(separator);
    } catch (Exception e) {
        LOGGER.debug("Unable to run operation {} on bean {} ", operation, separator);

    }
}

From source file:com.app.server.SARDeployer.java

/**
 * This method adds the url to the classloader.
 * @param warDirectory//from   w w  w  . j av a2 s .  com
 * @param classLoader
 */
/*private void AddUrlToClassLoader(File warDirectory,WebClassLoader classLoader){
   File webInfDirectory=new File(warDirectory.getAbsolutePath()+"/WEB-INF/lib/");
   //logger.info(webInfDirectory.getAbsolutePath());
   if(webInfDirectory.exists()){
 File[] jarfiles=webInfDirectory.listFiles();
 for(int jarcount=0;jarcount<jarfiles.length;jarcount++){
    //logger.info(jarfiles[jarcount]);
    if(jarfiles[jarcount].getName().endsWith(".jar")){
       try {
       //   //log.info("Adding absolute path "+jarfiles[jarcount].getAbsolutePath());
          new WebServer().addURL(new URL("file:"+jarfiles[jarcount].getAbsolutePath()),classLoader);
       } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }
 }
   }
}*/

public void deployService(File sarFile) {
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(sarFile)));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            //log.info(mbean.getObjectname());
            //log.info(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class service = Thread.currentThread().getContextClassLoader().loadClass(mbean.getCls());
            Object obj = service.newInstance();
            if (mbeanServer.isRegistered(objName)) {
                //mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbeanServer.unregisterMBean(objName);
            }
            mbeanServer.createMBean(service.getName(), objName);
            //mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbeanServer.setAttribute(objName, mbeanattribute);
                }
            }
            Attribute mbeanattribute = new Attribute("ObjectName", objName);
            mbeanServer.setAttribute(objName, mbeanattribute);
            if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                mbeanServer.invoke(objName, "init", new Object[] { deployerList },
                        new String[] { Vector.class.getName() });
                //this.deployerList.add(objName.getCanonicalName());

            }
            mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer },
                    new String[] { Vector.class.getName(), ServerConfig.class.getName(),
                            MBeanServer.class.getName() });
            mbeanServer.invoke(objName, "start", null, null);
        }
    } catch (Exception ex) {
        log.error("Could not able to deploy the SAR package " + sarFile.toURI(), ex);
        //ex.printStackTrace();
    }
}