Java Code Examples for javax.management.MalformedObjectNameException

The following examples show how to use javax.management.MalformedObjectNameException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: blazingcache   Source File: JMXUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Unregister the mbean providing the status related to the specified {@link CacheClient}.
 *
 * @param client the client on which status mbean has to be unregistered
 */
public static void unregisterClientStatusMXBean(final CacheClient client) {
    if (platformMBeanServer == null) {
        return;
    }
    final String cacheClientId = safeName(client.getClientId());

    try {
        final ObjectName name = new ObjectName("blazingcache.client.management:type=CacheClientStatus,CacheClient=" + cacheClientId);

        if (platformMBeanServer.isRegistered(name)) {
            try {
                platformMBeanServer.unregisterMBean(name);
            } catch (InstanceNotFoundException noProblem) {
                LOGGER.warning("Impossible to unregister non-registered mbean: " + name + ". Cause: " + noProblem);
            }
        }
    } catch (MalformedObjectNameException | MBeanRegistrationException e) {
        throw new BlazingCacheManagementException(REGISTRATION_FAILURE_MSG, e);
    }
}
 
Example 2
Source Project: Tomcat8-Source-Read   Source File: UserMBean.java    License: MIT License 6 votes vote down vote up
/**
 * @return the MBean Names of all groups this user is a member of.
 */
public String[] getGroups() {

    User user = (User) this.resource;
    ArrayList<String> results = new ArrayList<>();
    Iterator<Group> groups = user.getGroups();
    while (groups.hasNext()) {
        Group group = null;
        try {
            group = groups.next();
            ObjectName oname =
                MBeanUtils.createObjectName(managed.getDomain(), group);
            results.add(oname.toString());
        } catch (MalformedObjectNameException e) {
            IllegalArgumentException iae = new IllegalArgumentException
                ("Cannot create object name for group " + group);
            iae.initCause(e);
            throw iae;
        }
    }
    return results.toArray(new String[results.size()]);
}
 
Example 3
@Test
public void managerClearTest() throws MalformedObjectNameException {
	String counterName = "test.1";
	ObjectName counterObjectName = new ObjectName(DOMAIN + ":type=" + SimonInfo.COUNTER + ",name=" + counterName);

	String stopwatchName = "test.2";
	ObjectName stopwatchObjectName = new ObjectName(DOMAIN + ":type=" + SimonInfo.STOPWATCH + ",name=" + stopwatchName);

	Assert.assertFalse(mbs.isRegistered(counterObjectName));
	Assert.assertFalse(mbs.isRegistered(stopwatchObjectName));

	SimonManager.getCounter(counterName);
	Assert.assertTrue(mbs.isRegistered(counterObjectName));

	SimonManager.getStopwatch(stopwatchName);
	Assert.assertTrue(mbs.isRegistered(stopwatchObjectName));

	SimonManager.clear();
	Assert.assertFalse(mbs.isRegistered(counterObjectName));
	Assert.assertFalse(mbs.isRegistered(stopwatchObjectName));
}
 
Example 4
Source Project: tomcatsrc   Source File: MemoryUserDatabaseMBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the MBean Name for the specified group name (if any);
 * otherwise return <code>null</code>.
 *
 * @param groupname Group name to look up
 */
public String findGroup(String groupname) {

    UserDatabase database = (UserDatabase) this.resource;
    Group group = database.findGroup(groupname);
    if (group == null) {
        return (null);
    }
    try {
        ObjectName oname =
            MBeanUtils.createObjectName(managedGroup.getDomain(), group);
        return (oname.toString());
    } catch (MalformedObjectNameException e) {
        IllegalArgumentException iae = new IllegalArgumentException
            ("Cannot create object name for group [" + groupname + "]");
        iae.initCause(e);
        throw iae;
    }

}
 
Example 5
Source Project: rubix   Source File: CachingFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
public static void setLocalBookKeeper(BookKeeperService.Iface bookKeeper, String statsMbeanSuffix)
{
  bookKeeperFactory = new BookKeeperFactory(bookKeeper);
  if (!Strings.isNullOrEmpty(statsMbeanSuffix)) {
    String mBeanName = statsMBeanBaseName + "," + statsMbeanSuffix;
    MBeanExporter exporter = new MBeanExporter(ManagementFactory.getPlatformMBeanServer());
    try {
      if (ManagementFactory.getPlatformMBeanServer().isRegistered(new ObjectName(statsMBeanBaseName))) {
        exporter.unexport(statsMBeanBaseName);
      }
      if (!ManagementFactory.getPlatformMBeanServer().isRegistered(new ObjectName(mBeanName))) {
        exporter.export(mBeanName, statsMBean);
      }
    }
    catch (MalformedObjectNameException e) {
      log.error("Could not export stats mbean", e);
    }
  }
}
 
Example 6
/**
 * Creates an ObjectName representation of a {@link PathAddress}.
 * @param domain the JMX domain to use for the ObjectName. Cannot be {@code null}
 * @param pathAddress the address. Cannot be {@code null}
 * @param context contextual objection that allows this method to cache state across invocations. May be {@code null}
 * @return the ObjectName. Will not return {@code null}
 */
static ObjectName createObjectName(final String domain, final PathAddress pathAddress, ObjectNameCreationContext context) {

    if (pathAddress.size() == 0) {
        return ModelControllerMBeanHelper.createRootObjectName(domain);
    }
    final StringBuilder sb = new StringBuilder(domain);
    sb.append(":");
    boolean first = true;
    for (PathElement element : pathAddress) {
        if (first) {
            first = false;
        } else {
            sb.append(",");
        }
        escapeKey(ESCAPED_KEY_CHARACTERS, sb, element.getKey(), context);
        sb.append("=");
        escapeValue(sb, element.getValue(), context);
    }
    try {
        return ObjectName.getInstance(sb.toString());
    } catch (MalformedObjectNameException e) {
        throw JmxLogger.ROOT_LOGGER.cannotCreateObjectName(e, pathAddress, sb.toString());
    }
}
 
Example 7
Source Project: tomcatsrc   Source File: NamingResourcesMBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add a resource link reference for this web application.
 *
 * @param resourceLinkName New resource link reference name
 * @param type New resource link reference type
 */
public String addResourceLink(String resourceLinkName, String type)
    throws MalformedObjectNameException {
    
    NamingResources nresources = (NamingResources) this.resource;
    if (nresources == null) {
        return null;
    }
    ContextResourceLink resourceLink = 
                        nresources.findResourceLink(resourceLinkName);
    if (resourceLink != null) {
        throw new IllegalArgumentException
            ("Invalid resource link name - already exists'" + 
            resourceLinkName + "'");
    }
    resourceLink = new ContextResourceLink();
    resourceLink.setName(resourceLinkName);
    resourceLink.setType(type);
    nresources.addResourceLink(resourceLink);
    
    // Return the corresponding MBean name
    ManagedBean managed = registry.findManagedBean("ContextResourceLink");
    ObjectName oname =
        MBeanUtils.createObjectName(managed.getDomain(), resourceLink);
    return (oname.toString());
}
 
Example 8
Source Project: herddb   Source File: JMXUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void unregisterDBManagerStatsMXBean() {
    if (platformMBeanServer == null) {
        return;
    }

    try {
        ObjectName name = new ObjectName("herddb.server:type=Server");
        if (platformMBeanServer.isRegistered(name)) {
            try {
                platformMBeanServer.unregisterMBean(name);
            } catch (InstanceNotFoundException noProblem) {
            }
        }
    } catch (MalformedObjectNameException | MBeanRegistrationException e) {
        throw new HerdDBInternalException("Could not unregister MXBean " + e);
    }
}
 
Example 9
Source Project: tomcatsrc   Source File: AbstractProtocol.java    License: Apache License 2.0 6 votes vote down vote up
private ObjectName createObjectName() throws MalformedObjectNameException {
    // Use the same domain as the connector
    domain = adapter.getDomain();

    if (domain == null) {
        return null;
    }

    StringBuilder name = new StringBuilder(getDomain());
    name.append(":type=ProtocolHandler,port=");
    int port = getPort();
    if (port > 0) {
        name.append(getPort());
    } else {
        name.append("auto-");
        name.append(getNameIndex());
    }
    InetAddress address = getAddress();
    if (address != null) {
        name.append(",address=");
        name.append(ObjectName.quote(address.getHostAddress()));
    }
    return new ObjectName(name.toString());
}
 
Example 10
Source Project: blazingcache   Source File: JMXUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static <K, V> void registerStatisticsMXBean(BlazingCacheCache<K, V> cache, BlazingCacheStatisticsMXBean<K, V> bean) {
    if (platformMBeanServer == null) {
        throw new CacheException("PlatformMBeanServer not available", mBeanServerLookupError);
    }
    String cacheManagerName = safeName(cache.getCacheManager().getURI().toString());
    String cacheName = safeName(cache.getName());

    try {
        ObjectName name = new ObjectName("javax.cache:type=CacheStatistics,CacheManager=" + cacheManagerName + ",Cache=" + cacheName);

        if (platformMBeanServer.isRegistered(name)) {
            try {
                platformMBeanServer.unregisterMBean(name);
            } catch (InstanceNotFoundException noProblem) {
            }
        }
        platformMBeanServer.registerMBean(bean, name);
    } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
        throw new CacheException("Could not register MXBean " + e);
    }
}
 
Example 11
/**
 * Reads the {@code ObjectName} from the source-level metadata associated
 * with the managed resource's {@code Class}.
 */
@Override
public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException {
	Class<?> managedClass = AopUtils.getTargetClass(managedBean);
	ManagedResource mr = this.attributeSource.getManagedResource(managedClass);

	// Check that an object name has been specified.
	if (mr != null && StringUtils.hasText(mr.getObjectName())) {
		return ObjectNameManager.getInstance(mr.getObjectName());
	}
	else {
		try {
			return ObjectNameManager.getInstance(beanKey);
		}
		catch (MalformedObjectNameException ex) {
			String domain = this.defaultDomain;
			if (domain == null) {
				domain = ClassUtils.getPackageName(managedClass);
			}
			Hashtable<String, String> properties = new Hashtable<String, String>();
			properties.put("type", ClassUtils.getShortName(managedClass));
			properties.put("name", beanKey);
			return ObjectNameManager.getInstance(domain, properties);
		}
	}
}
 
Example 12
Source Project: Tomcat7.0.67   Source File: UserMBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the MBean Names of all groups this user is a member of.
 */
public String[] getGroups() {

    User user = (User) this.resource;
    ArrayList<String> results = new ArrayList<String>();
    Iterator<Group> groups = user.getGroups();
    while (groups.hasNext()) {
        Group group = null;
        try {
            group = groups.next();
            ObjectName oname =
                MBeanUtils.createObjectName(managed.getDomain(), group);
            results.add(oname.toString());
        } catch (MalformedObjectNameException e) {
            IllegalArgumentException iae = new IllegalArgumentException
                ("Cannot create object name for group " + group);
            iae.initCause(e);
            throw iae;
        }
    }
    return results.toArray(new String[results.size()]);

}
 
Example 13
Source Project: scheduling   Source File: RMRest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Map<String, Map<String, Object>> getNodesMBeanHistory(String sessionId, List<String> nodesJmxUrl,
        String objectName, List<String> attrs, String range)
        throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException,
        NotConnectedException, MalformedObjectNameException, NullPointerException, MBeanException {

    // checking that still connected to the RM
    RMProxyUserInterface rmProxy = checkAccess(sessionId);
    return nodesJmxUrl.stream().collect(Collectors.toMap(nodeJmxUrl -> nodeJmxUrl, nodeJmxUrl -> {
        try {
            return processHistoryResult(rmProxy.getNodeMBeanHistory(nodeJmxUrl, objectName, attrs, range), range);
        } catch (Exception e) {
            LOGGER.error(e);
            return Collections.EMPTY_MAP;
        }
    }));
}
 
Example 14
Source Project: cxf   Source File: ManagementConsole.java    License: Apache License 2.0 5 votes vote down vote up
ObjectName getEndpointObjectName()
    throws MalformedObjectNameException, NullPointerException {
    StringBuilder buffer = new StringBuilder(128);
    buffer.append(ManagementConstants.DEFAULT_DOMAIN_NAME).append(":type=Bus.Service.Endpoint,");
    buffer.append(ManagementConstants.SERVICE_NAME_PROP + "=\"" + serviceName + "\",");
    buffer.append(ManagementConstants.PORT_NAME_PROP + "=\"" + portName + "\",*");
    return new ObjectName(buffer.toString());
}
 
Example 15
Source Project: gemfirexd-oss   Source File: LauncherLifecycleCommands.java    License: Apache License 2.0 5 votes vote down vote up
protected MemberMXBean getMemberMXBean(final String serviceName, final String member) throws IOException {
  assertState(isConnectedAndReady(), "Gfsh must be connected in order to get proxy to a GemFire Member MBean.");

  MemberMXBean memberBean = null;

  try {
    String objectNamePattern = ManagementConstants.OBJECTNAME__PREFIX;

    objectNamePattern += (StringUtils.isBlank(serviceName) ? StringUtils.EMPTY_STRING
      : "service=" + serviceName + StringUtils.COMMA_DELIMITER);
    objectNamePattern += "type=Member,*";

    // NOTE throws a MalformedObjectNameException, however, this should not happen since the ObjectName is constructed
    // here in a conforming pattern
    final ObjectName objectName = ObjectName.getInstance(objectNamePattern);

    final QueryExp query = Query.or(
      Query.eq(Query.attr("Name"), Query.value(member)),
      Query.eq(Query.attr("Id"), Query.value(member))
    );

    final Set<ObjectName> memberObjectNames = getGfsh().getOperationInvoker().queryNames(objectName, query);

    if (!memberObjectNames.isEmpty()) {
      memberBean = getGfsh().getOperationInvoker().getMBeanProxy(memberObjectNames.iterator().next(), MemberMXBean.class);
    }
  }
  catch (MalformedObjectNameException e) {
    getGfsh().logSevere(e.getMessage(), e);
  }

  return memberBean;
}
 
Example 16
Source Project: openjdk-jdk9   Source File: Util.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static ObjectName newObjectName(String string) {
    try {
        return new ObjectName(string);
    } catch (MalformedObjectNameException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 17
Source Project: gemfirexd-oss   Source File: LauncherLifecycleCommands.java    License: Apache License 2.0 5 votes vote down vote up
protected MemberMXBean getMemberMXBean(final String serviceName, final String member) throws IOException {
  assertState(isConnectedAndReady(), "Gfsh must be connected in order to get proxy to a GemFire Member MBean.");

  MemberMXBean memberBean = null;

  try {
    String objectNamePattern = ManagementConstants.OBJECTNAME__PREFIX;

    objectNamePattern += (StringUtils.isBlank(serviceName) ? StringUtils.EMPTY_STRING
      : "service=" + serviceName + StringUtils.COMMA_DELIMITER);
    objectNamePattern += "type=Member,*";

    // NOTE throws a MalformedObjectNameException, however, this should not happen since the ObjectName is constructed
    // here in a conforming pattern
    final ObjectName objectName = ObjectName.getInstance(objectNamePattern);

    final QueryExp query = Query.or(
      Query.eq(Query.attr("Name"), Query.value(member)),
      Query.eq(Query.attr("Id"), Query.value(member))
    );

    final Set<ObjectName> memberObjectNames = getGfsh().getOperationInvoker().queryNames(objectName, query);

    if (!memberObjectNames.isEmpty()) {
      memberBean = getGfsh().getOperationInvoker().getMBeanProxy(memberObjectNames.iterator().next(), MemberMXBean.class);
    }
  }
  catch (MalformedObjectNameException e) {
    getGfsh().logSevere(e.getMessage(), e);
  }

  return memberBean;
}
 
Example 18
private JMXConnector connectToServer(JMXConnectorServer server) throws IOException, MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, ReflectionException, MBeanException {
    JMXServiceURL url = server.getAddress();
    Map<String, Object> env = new HashMap<String, Object>();
    JMXConnector connector = JMXConnectorFactory.connect(url, env);

    System.out.println("DEBUG: Client connected to RMI at: " + url);

    return connector;
}
 
Example 19
private static MBeanPermission getMBeanPermission(Class mbeanClass, String objectName, String action) {
    try {
        return new MBeanPermission(mbeanClass.getName(), "-", ObjectName.getInstance(objectName), action);
    } catch (MalformedObjectNameException | NullPointerException ex) {
    }
    return new MBeanPermission(mbeanClass + "#-[" + objectName + "]", action);
}
 
Example 20
Source Project: cxf   Source File: InstrumentationManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private ObjectName getDelegateName() throws JMException {
    try {
        return (ObjectName)MBeanServerDelegate.class.getField("DELEGATE_NAME").get(null);
    } catch (Throwable t) {
        //ignore, likely on Java5
    }
    try {
        return new ObjectName("JMImplementation:type=MBeanServerDelegate");
    } catch (MalformedObjectNameException e) {
        JMException jme = new JMException(e.getMessage());
        jme.initCause(e);
        throw jme;
    }
}
 
Example 21
Source Project: java-technology-stack   Source File: LiveBeansViewTests.java    License: MIT License 5 votes vote down vote up
@Test
public void registerUnregisterSingleContext() throws MalformedObjectNameException {
	this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, this.name.getMethodName());
	ConfigurableApplicationContext context = createApplicationContext("app");
	assertEquals(0, searchLiveBeansViewMeans().size());
	LiveBeansView.registerApplicationContext(context);
	assertSingleLiveBeansViewMbean("app");
	LiveBeansView.unregisterApplicationContext(context);
	assertEquals(0, searchLiveBeansViewMeans().size());
}
 
Example 22
@Override
public String getDatabaseProperty(final String key) throws SQLException{
    DatabasePropertyManagement dpm = null;
    try {
        dpm = JMXUtils.getLocalMBeanProxy(JMXUtils.DATABASE_PROPERTY_MANAGEMENT, DatabasePropertyManagement.class);
    }catch(MalformedObjectNameException|IOException e){
        throw PublicAPI.wrapStandardException(Exceptions.parseException(e));
    }
    return dpm.getDatabaseProperty(key);
}
 
Example 23
Source Project: openjdk-8   Source File: Util.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static ObjectName newObjectName(String string) {
    try {
        return new ObjectName(string);
    } catch (MalformedObjectNameException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 24
Source Project: Tomcat8-Source-Read   Source File: BasicDataSource.java    License: MIT License 5 votes vote down vote up
@Override
public ObjectName preRegister(final MBeanServer server, final ObjectName objectName) {
    final String requestedName = getJmxName();
    if (requestedName != null) {
        try {
            registeredJmxObjectName = ObjectNameWrapper.wrap(requestedName);
        } catch (final MalformedObjectNameException e) {
            log.warn("The requested JMX name [" + requestedName + "] was not valid and will be ignored.");
        }
    }
    if (registeredJmxObjectName == null) {
        registeredJmxObjectName = ObjectNameWrapper.wrap(objectName);
    }
    return ObjectNameWrapper.unwrap(registeredJmxObjectName);
}
 
Example 25
Source Project: LagMonitor   Source File: DumpCommand.java    License: MIT License 5 votes vote down vote up
public Object invokeBeanCommand(String beanName, String command, Object[] args, String[] signature)
        throws MalformedObjectNameException, MBeanException, InstanceNotFoundException, ReflectionException {
    MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName beanObject = ObjectName.getInstance(beanName);

    return beanServer.invoke(beanObject, command, args, signature);
}
 
Example 26
Source Project: ignite   Source File: CacheManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param cacheName Cache name.
 * @param objName Object name.
 * @return Object name instance.
 */
private ObjectName getObjectName(String cacheName, String objName) {
    String mBeanName = "javax.cache:type=" + objName + ",CacheManager="
        + uri.toString().replaceAll(",|:|=|\n", ".")
        + ",Cache=" + cacheName.replaceAll(",|:|=|\n", ".");

    try {
        return new ObjectName(mBeanName);
    }
    catch (MalformedObjectNameException e) {
        throw new CacheException("Failed to create MBean name: " + mBeanName, e);
    }
}
 
Example 27
Source Project: activemq-artemis   Source File: JMXAccessControlListTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMutipleBasicRoles() throws MalformedObjectNameException {
   JMXAccessControlList controlList = new JMXAccessControlList();
   controlList.addToRoleAccess("org.myDomain", null, "listSomething", "admin", "view", "update");
   List<String> roles = controlList.getRolesForObject(new ObjectName("org.myDomain:*"), "listSomething");
   Assert.assertArrayEquals(roles.toArray(), new String[]{"admin", "view", "update"});
}
 
Example 28
public JmxNotificationSubscriptionConfig<T> objectName(String val) {
    try {
        return objectName(new ObjectName(val));
    } catch (MalformedObjectNameException e) {
        throw new IllegalArgumentException("Invalid object name ("+val+")", e);
    }
}
 
Example 29
Source Project: javamelody   Source File: JCacheInformations.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<ObjectName> getJsr107CacheStatistics() {
	try {
		final ObjectName objectName = new ObjectName("javax.cache:type=CacheStatistics,*");
		return MBEAN_SERVER.queryNames(objectName, null);
	} catch (final MalformedObjectNameException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 30
/**
 * A validation test against the rules above to make sure they are INVALID. 
 */
@Test(expected=RuleEvaluationException.class)
public void testInvalidRules3() throws MBeanRegistrationException, InstanceNotFoundException,
    MalformedObjectNameException, NullPointerException, InterruptedException,
    RuleEvaluationException {

  evaluateRule(INVALID_RULE_3);
}
 
Example 31
Source Project: presto   Source File: JmxMetadata.java    License: Apache License 2.0 5 votes vote down vote up
public static String toPattern(String tableName)
{
    try {
        if (!tableName.contains("*")) {
            return Pattern.quote(new ObjectName(tableName).getCanonicalName());
        }
        return Streams.stream(Splitter.on('*').split(tableName))
                .map(Pattern::quote)
                .collect(Collectors.joining(".*"));
    }
    catch (MalformedObjectNameException exception) {
        LOGGER.debug(exception, "Invalid ObjectName");
        throw new PrestoException(JMX_INVALID_TABLE_NAME, "Not a valid ObjectName " + tableName);
    }
}
 
Example 32
Source Project: james-project   Source File: LineHandlerStats.java    License: Apache License 2.0 5 votes vote down vote up
public LineHandlerStats(String jmxName, String handlerName) throws NotCompliantMBeanException, MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException {
    super(HandlerStatsMBean.class);
    this.handlerName = handlerName;

    this.name = "org.apache.james:type=server,name=" + jmxName + ",chain=handlerchain,handler=linehandler,linehandler=" + handlerName;
    mbeanserver = ManagementFactory.getPlatformMBeanServer();
    ObjectName baseObjectName = new ObjectName(name);
    mbeanserver.registerMBean(this, baseObjectName);
}
 
Example 33
Source Project: spring-analysis-note   Source File: ObjectNameManager.java    License: MIT License 5 votes vote down vote up
/**
 * Retrieve the {@code ObjectName} instance corresponding to the supplied name.
 * @param objectName the {@code ObjectName} in {@code ObjectName} or
 * {@code String} format
 * @return the {@code ObjectName} instance
 * @throws MalformedObjectNameException in case of an invalid object name specification
 * @see ObjectName#ObjectName(String)
 * @see ObjectName#getInstance(String)
 */
public static ObjectName getInstance(Object objectName) throws MalformedObjectNameException {
	if (objectName instanceof ObjectName) {
		return (ObjectName) objectName;
	}
	if (!(objectName instanceof String)) {
		throw new MalformedObjectNameException("Invalid ObjectName value type [" +
				objectName.getClass().getName() + "]: only ObjectName and String supported.");
	}
	return getInstance((String) objectName);
}
 
Example 34
Source Project: spliceengine   Source File: JMXUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static List<ManagedCacheMBean> getTotalManagedCache(List<Pair<String,JMXConnector>> mbscArray) throws MalformedObjectNameException, IOException {
    List<ManagedCacheMBean> managedCache = new ArrayList<>();
    List<ManagedCache> mc = new ArrayList<>();
    for (Pair<String,JMXConnector> mbsc: mbscArray) {
        managedCache.add(getNewMBeanProxy(mbsc.getSecond(),TOTAL_MANAGED_CACHE, ManagedCacheMBean.class));
    }
    return managedCache;
}
 
Example 35
Source Project: stratio-cassandra   Source File: NodeProbe.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve Proxy metrics
 * @param metricName Exceptions, Load, TotalHints or TotalHintsInProgress.
 */
public long getStorageMetric(String metricName)
{
    try
    {
        return JMX.newMBeanProxy(mbeanServerConn,
                new ObjectName("org.apache.cassandra.metrics:type=Storage,name=" + metricName),
                JmxReporter.CounterMBean.class).getCount();
    }
    catch (MalformedObjectNameException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 36
@Override
public void setWritePoolMaxThreadCount(final int maxThreadCount) throws SQLException{
    operate(new JMXServerOperation(){
        @Override
        public void operate(List<Pair<String, JMXConnector>> connections) throws MalformedObjectNameException, IOException, SQLException{
            List<ThreadPoolStatus> threadPools=JMXUtils.getMonitoredThreadPools(connections);
            for(ThreadPoolStatus threadPool : threadPools){
                threadPool.setMaxThreadCount(maxThreadCount);
            }
        }
    });
}
 
Example 37
Source Project: spring-analysis-note   Source File: IdentityNamingStrategy.java    License: MIT License 5 votes vote down vote up
/**
 * Returns an instance of {@code ObjectName} based on the identity
 * of the managed resource.
 */
@Override
public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException {
	String domain = ClassUtils.getPackageName(managedBean.getClass());
	Hashtable<String, String> keys = new Hashtable<>();
	keys.put(TYPE_KEY, ClassUtils.getShortName(managedBean.getClass()));
	keys.put(HASH_CODE_KEY, ObjectUtils.getIdentityHexString(managedBean));
	return ObjectNameManager.getInstance(domain, keys);
}
 
Example 38
Source Project: helix   Source File: MBeanRegistrar.java    License: Apache License 2.0 5 votes vote down vote up
public static ObjectName buildObjectName(String domain, String... keyValuePairs)
    throws MalformedObjectNameException {
  if (keyValuePairs.length < 2 || keyValuePairs.length % 2 != 0) {
    throw new IllegalArgumentException("key-value pairs for ObjectName must contain even "
        + "number of String and at least 2 String");
  }

  StringBuilder objectNameStr = new StringBuilder();
  for (int i = 0; i < keyValuePairs.length; i += 2) {
    objectNameStr.append(
        String.format(i == 0 ? "%s=%s" : ",%s=%s", keyValuePairs[i], keyValuePairs[i + 1]));
  }

  return new ObjectName(String.format("%s:%s", domain, objectNameStr.toString()));
}
 
Example 39
Source Project: gemfirexd-oss   Source File: AgentImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new Agent using the specified configuration.
 *
 * @param agentConfig instance of configuration for Agent
 * @throws com.gemstone.gemfire.admin.AdminException TODO-javadocs
 * @throws IllegalArgumentException if agentConfig is null
 */
public AgentImpl(AgentConfig agentConfig)
  throws AdminException, IllegalArgumentException {
  addShutdownHook();
  if (agentConfig == null) {
    throw new IllegalArgumentException(LocalizedStrings.AgentImpl_AGENTCONFIG_MUST_NOT_BE_NULL.toLocalizedString());
  }
  this.agentConfig = (AgentConfigImpl)agentConfig;
  this.mbeanName   = MBEAN_NAME_PREFIX + MBeanUtil.makeCompliantMBeanNameProperty("Agent");

  try {
    this.objectName = new ObjectName(this.mbeanName);
  } catch (MalformedObjectNameException ex) {
    String s = LocalizedStrings.AgentImpl_WHILE_CREATING_OBJECTNAME_0.toLocalizedString(new Object[] { this.mbeanName });
    throw new AdminException(s, ex);
  }

  this.propertyFile = this.agentConfig.getPropertyFile().getAbsolutePath();

  // bind address only affects how the Agent VM connects to the system...
  // It should be set only once in the agent lifecycle
  this.agentConfig.setBindAddress(getBindAddress());

  // init the logger
  initLogWriter();

  mBeanServer = MBeanUtil.start();

  MBeanUtil.createMBean(this);

  initializeHelperMbean();
}
 
Example 40
Source Project: spring-analysis-note   Source File: MetadataNamingStrategy.java    License: MIT License 5 votes vote down vote up
/**
 * Reads the {@code ObjectName} from the source-level metadata associated
 * with the managed resource's {@code Class}.
 */
@Override
public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException {
	Assert.state(this.attributeSource != null, "No JmxAttributeSource set");
	Class<?> managedClass = AopUtils.getTargetClass(managedBean);
	ManagedResource mr = this.attributeSource.getManagedResource(managedClass);

	// Check that an object name has been specified.
	if (mr != null && StringUtils.hasText(mr.getObjectName())) {
		return ObjectNameManager.getInstance(mr.getObjectName());
	}
	else {
		Assert.state(beanKey != null, "No ManagedResource attribute and no bean key specified");
		try {
			return ObjectNameManager.getInstance(beanKey);
		}
		catch (MalformedObjectNameException ex) {
			String domain = this.defaultDomain;
			if (domain == null) {
				domain = ClassUtils.getPackageName(managedClass);
			}
			Hashtable<String, String> properties = new Hashtable<>();
			properties.put("type", ClassUtils.getShortName(managedClass));
			properties.put("name", beanKey);
			return ObjectNameManager.getInstance(domain, properties);
		}
	}
}