Java Code Examples for javax.management.ObjectName

The following are top voted examples for showing how to use javax.management.ObjectName. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hadoop-oss   File: MBeanUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Register the MBean using our standard MBeanName format
 * "hadoop:service=<serviceName>,name=<nameName>"
 * Where the <serviceName> and <nameName> are the supplied parameters
 *    
 * @param serviceName
 * @param nameName
 * @param theMbean - the MBean to register
 * @return the named used to register the MBean
 */	
static public ObjectName registerMBean(final String serviceName, 
  							final String nameName,
  							final Object theMbean) {
  final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  ObjectName name = getMBeanName(serviceName, nameName);
  try {
    mbs.registerMBean(theMbean, name);
    return name;
  } catch (InstanceAlreadyExistsException ie) {
    // Ignore if instance already exists 
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 2
Project: flume-release-1.7.0   File: TestMonitoredCounterGroup.java   Source Code and License 6 votes vote down vote up
private void assertChCounterState(ObjectName on, long channelSize,
    long eventPutAttempt, long eventTakeAttempt, long eventPutSuccess,
    long eventTakeSuccess) throws Exception {
  Assert.assertEquals("ChChannelSize",
      getChChannelSize(on),
      channelSize);
  Assert.assertEquals("ChEventPutAttempt",
      getChEventPutAttempt(on),
      eventPutAttempt);
  Assert.assertEquals("ChEventTakeAttempt",
      getChEventTakeAttempt(on),
      eventTakeAttempt);
  Assert.assertEquals("ChEventPutSuccess",
      getChEventPutSuccess(on),
      eventPutSuccess);
  Assert.assertEquals("ChEventTakeSuccess",
      getChEventTakeSuccess(on),
      eventTakeSuccess);
}
 
Example 3
Project: hashsdn-controller   File: DynamicWritableWrapperTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testObjectNameSetterWithONContainingTransaction_shouldBeTranslatedToReadOnlyON() throws Exception {
    TestingParallelAPSPModuleFactory testingParallelAPSPConfigBeanFactory = new TestingParallelAPSPModuleFactory();
    TestingParallelAPSPModule apspConfigBean = testingParallelAPSPConfigBeanFactory.createModule("", null, null);
    ModuleIdentifier moduleIdentifier2 = new ModuleIdentifier("apsp", "parallel");
    ObjectName dynON2 = ObjectNameUtil.createReadOnlyModuleON(moduleIdentifier2);
    AbstractDynamicWrapper dyn = getDynamicWrapper(apspConfigBean, moduleIdentifier2);
    platformMBeanServer.registerMBean(dyn, dynON2);
    try {
        TestingParallelAPSPConfigMXBean proxy = JMX.newMBeanProxy(platformMBeanServer, dynON2,
                TestingParallelAPSPConfigMXBean.class);
        ObjectName withTransactionName = ObjectNameUtil.createTransactionModuleON("transaction1", "moduleName",
                "instanceName");
        proxy.setThreadPool(withTransactionName);
        ObjectName withoutTransactionName = ObjectNameUtil.withoutTransactionName(withTransactionName);
        assertEquals(withoutTransactionName, proxy.getThreadPool());
    } finally {
        platformMBeanServer.unregisterMBean(dynON2);
    }
}
 
Example 4
Project: openjdk-jdk10   File: DefaultMBeanServerInterceptor.java   Source Code and License 6 votes vote down vote up
private static ObjectName preRegister(
        DynamicMBean mbean, MBeanServer mbs, ObjectName name)
        throws InstanceAlreadyExistsException, MBeanRegistrationException {

    ObjectName newName = null;

    try {
        if (mbean instanceof MBeanRegistration)
            newName = ((MBeanRegistration) mbean).preRegister(mbs, name);
    } catch (Throwable t) {
        throwMBeanRegistrationException(t, "in preRegister method");
    }

    if (newName != null) return newName;
    else return name;
}
 
Example 5
Project: jerrydog   File: MBeanUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Create, register, and return an MBean for this
 * <code>UserDatabase</code> object.
 *
 * @param userDatabase The UserDatabase to be managed
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public static ModelMBean createMBean(UserDatabase userDatabase)
    throws Exception {

    String mname = createManagedName(userDatabase);
    ManagedBean managed = registry.findManagedBean(mname);
    if (managed == null) {
        Exception e = new Exception("ManagedBean is not found with "+mname);
        throw new MBeanException(e);
    }
    String domain = managed.getDomain();
    if (domain == null)
        domain = mserver.getDefaultDomain();
    ModelMBean mbean = managed.createMBean(userDatabase);
    ObjectName oname = createObjectName(domain, userDatabase);
    mserver.registerMBean(mbean, oname);
    return (mbean);

}
 
Example 6
Project: lams   File: MBeanExporter.java   Source Code and License 6 votes vote down vote up
/**
 * Unregister the configured {@link NotificationListener NotificationListeners}
 * from the {@link MBeanServer}.
 */
private void unregisterNotificationListeners() {
	for (Map.Entry<NotificationListenerBean, ObjectName[]> entry : this.registeredNotificationListeners.entrySet()) {
		NotificationListenerBean bean = entry.getKey();
		ObjectName[] mappedObjectNames = entry.getValue();
		for (ObjectName mappedObjectName : mappedObjectNames) {
			try {
				this.server.removeNotificationListener(mappedObjectName, bean.getNotificationListener(),
						bean.getNotificationFilter(), bean.getHandback());
			}
			catch (Exception ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Unable to unregister NotificationListener", ex);
				}
			}
		}
	}
	this.registeredNotificationListeners.clear();
}
 
Example 7
Project: tomcat7   File: Registry.java   Source Code and License 6 votes vote down vote up
/** Find the operation info for a method
 * 
 * @param oname
 * @param opName
 * @return the operation info for the specified operation
 */ 
public MBeanOperationInfo getMethodInfo( ObjectName oname, String opName )
{
    MBeanInfo info=null;
    try {
        info=server.getMBeanInfo(oname);
    } catch (Exception e) {
        log.info( "Can't find metadata " + oname );
        return null;
    }
    MBeanOperationInfo attInfo[]=info.getOperations();
    for( int i=0; i<attInfo.length; i++ ) {
        if( opName.equals(attInfo[i].getName())) {
            return attInfo[i];
        }
    }
    return null;
}
 
Example 8
Project: hadoop   File: TestJMXGet.java   Source Code and License 6 votes vote down vote up
/**
 * test JMX connection to DataNode..
 * @throws Exception 
 */
@Test
public void testDataNode() throws Exception {
  int numDatanodes = 2;
  cluster = new MiniDFSCluster.Builder(config).numDataNodes(numDatanodes).build();
  cluster.waitActive();

  writeFile(cluster.getFileSystem(), new Path("/test"), 2);

  JMXGet jmx = new JMXGet();
  String serviceName = "DataNode";
  jmx.setService(serviceName);
  jmx.init();
  assertEquals(fileSize, Integer.parseInt(jmx.getValue("BytesWritten")));

  cluster.shutdown();
  MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
  ObjectName query = new ObjectName("Hadoop:service=" + serviceName + ",*");
  Set<ObjectName> names = mbsc.queryNames(query, null);
  assertTrue("No beans should be registered for " + serviceName, names.isEmpty());
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: StandardPipeline.java   Source Code and License 6 votes vote down vote up
public ObjectName[] getValveObjectNames() {

        ArrayList<ObjectName> valveList = new ArrayList<ObjectName>();
        Valve current = first;
        if (current == null) {
            current = basic;
        }
        while (current != null) {
            if (current instanceof ValveBase) {
                valveList.add(((ValveBase) current).getObjectName());
            }
            current = current.getNext();
        }

        return valveList.toArray(new ObjectName[0]);

    }
 
Example 10
Project: OpenJSharp   File: DefaultMBeanServerInterceptor.java   Source Code and License 6 votes vote down vote up
/**
 * <p>Return the named {@link java.lang.ClassLoader}.
 * @param loaderName The ObjectName of the ClassLoader.
 * @return The named ClassLoader.
 * @exception InstanceNotFoundException if the named ClassLoader
 * is not found.
 */
public ClassLoader getClassLoader(ObjectName loaderName)
        throws InstanceNotFoundException {

    if (loaderName == null) {
        checkMBeanPermission((String) null, null, null, "getClassLoader");
        return server.getClass().getClassLoader();
    }

    DynamicMBean instance = getMBean(loaderName);
    checkMBeanPermission(instance, null, loaderName, "getClassLoader");

    Object resource = getResource(instance);

    /* Check if the given MBean is a ClassLoader */
    if (!(resource instanceof ClassLoader))
        throw new InstanceNotFoundException(loaderName.toString() +
                                            " is not a classloader");

    return (ClassLoader) resource;
}
 
Example 11
Project: jerrydog   File: MemoryUserDatabaseMBean.java   Source Code and License 6 votes vote down vote up
/**
 * Return the MBean Name for the specified role name (if any);
 * otherwise return <code>null</code>.
 *
 * @param rolename Role name to look up
 */
public String findRole(String rolename) {

    UserDatabase database = (UserDatabase) this.resource;
    Role role = database.findRole(rolename);
    if (role == null) {
        return (null);
    }
    try {
        ObjectName oname =
            MBeanUtils.createObjectName(managedRole.getDomain(), role);
        return (oname.toString());
    } catch (MalformedObjectNameException e) {
        throw new IllegalArgumentException
            ("Cannot create object name for role " + role);
    }

}
 
Example 12
Project: jerrydog   File: MBeanUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Create, register, and return an MBean for this
 * <code>Context</code> object.
 *
 * @param context The Context to be managed
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public static ModelMBean createMBean(Context context)
    throws Exception {

    String mname = createManagedName(context);
    ManagedBean managed = registry.findManagedBean(mname);
    if (managed == null) {
        Exception e = new Exception("ManagedBean is not found with "+mname);
        throw new MBeanException(e);
    }
    String domain = managed.getDomain();
    if (domain == null)
        domain = mserver.getDefaultDomain();
    ModelMBean mbean = managed.createMBean(context);
    ObjectName oname = createObjectName(domain, context);
    mserver.registerMBean(mbean, oname);
    return (mbean);

}
 
Example 13
Project: Pogamut3   File: PogamutMBeanServer.java   Source Code and License 6 votes vote down vote up
@Override
public synchronized void removeNotificationListener(ObjectName name,
		NotificationListener listener) throws InstanceNotFoundException,
		ListenerNotFoundException {		
	mbs.removeNotificationListener(name, listener);
	
	// TODO: slow implementation ... but fast one takes a lot of time to do :-)
	Iterator<Listener2> iter = listeners2.iterator();
	while(iter.hasNext()) {
		Listener2 l = iter.next();
		if (SafeEquals.equals(name, l.name) && SafeEquals.equals(listener, l.listener)) {
			listeners.remove(l);
			unregisteredListeners.remove(l);
			iter.remove();
		}
	}
}
 
Example 14
Project: lams   File: MBeanFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Create a new JNDI Realm.
 *
 * @param parent MBean Name of the associated parent component
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createJNDIRealm(String parent)
    throws Exception {

     // Create a new JNDIRealm instance
    JNDIRealm realm = new JNDIRealm();

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    ContainerBase containerBase = getParentContainerFromParent(pname);
    // Add the new instance to its parent component
    containerBase.setRealm(realm);
    // Return the corresponding MBean name
    ObjectName oname = realm.getObjectName();

    if (oname != null) {
        return (oname.toString());
    } else {
        return null;
    }   


}
 
Example 15
Project: lazycat   File: GroupMBean.java   Source Code and License 6 votes vote down vote up
/**
 * Return the MBean Names of all users that are members of this group.
 */
public String[] getUsers() {

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

}
 
Example 16
Project: OpenJSharp   File: DefaultMBeanServerInterceptor.java   Source Code and License 6 votes vote down vote up
public ObjectInstance registerMBean(Object object, ObjectName name)
    throws InstanceAlreadyExistsException, MBeanRegistrationException,
    NotCompliantMBeanException  {

    // ------------------------------
    // ------------------------------
    Class<?> theClass = object.getClass();

    Introspector.checkCompliance(theClass);

    final String infoClassName = getNewMBeanClassName(object);

    checkMBeanPermission(infoClassName, null, name, "registerMBean");
    checkMBeanTrustPermission(theClass);

    return registerObject(infoClassName, object, name);
}
 
Example 17
Project: jdk8u-jdk   File: ApplyWildcardTest.java   Source Code and License 6 votes vote down vote up
private static int runPositiveTests() {
    int error = 0;
    for (int i = 0; i < positiveTests.length; i++) {
        System.out.println("----------------------------------------------");
        try {
            ObjectName on1 = ObjectName.getInstance(positiveTests[i][0]);
            ObjectName on2 = ObjectName.getInstance(positiveTests[i][1]);
            System.out.println("\"" + on1 + "\".apply(\"" + on2 + "\")");
            boolean result = on1.apply(on2);
            System.out.println("Result = " + result);
            if (result == false) {
                error++;
                System.out.println("Test failed!");
            } else {
                System.out.println("Test passed!");
            }
        } catch (Exception e) {
            error++;
            System.out.println("Got Unexpected Exception = " + e.toString());
            System.out.println("Test failed!");
        }
        System.out.println("----------------------------------------------");
    }
    return error;
}
 
Example 18
Project: jdk8u-jdk   File: Repository.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves the named object contained in repository
 * from the given objectname.
 */
private NamedObject retrieveNamedObject(ObjectName name) {

    // No patterns inside reposit
    if (name.isPattern()) return null;

    // Extract the domain name.
    String dom = name.getDomain().intern();

    // Default domain case
    if (dom.length() == 0) {
        dom = domain;
    }

    Map<String,NamedObject> moiTb = domainTb.get(dom);
    if (moiTb == null) {
        return null; // No domain containing registered object names
    }

    return moiTb.get(name.getCanonicalKeyPropertyListString());
}
 
Example 19
Project: OpenJSharp   File: ClientHandler.java   Source Code and License 6 votes vote down vote up
public ClientHandler(CommunicatorServer server, int id, MBeanServer f, ObjectName n) {
    adaptorServer = server ;
    requestId = id ;
    mbs = f ;
    objectName = n ;
    interruptCalled = false ;
    dbgTag = makeDebugTag() ;
    //if (mbs == null ){
    //thread = new Thread (this) ;
    thread =  createThread(this);

    //} else {
    //thread = mbs.getThreadAllocatorSrvIf().obtainThread(objectName,this) ;
    //}
    // Note: the thread will be started by the subclass.
}
 
Example 20
Project: lams   File: JMXAccessorCondition.java   Source Code and License 5 votes vote down vote up
/**
 * Get value from MBeans attribute 
 * @return The value
 */
protected String accessJMXValue() {
    try {
        Object result = getJMXConnection().getAttribute(
                new ObjectName(name), attribute);
        if(result != null)
            return result.toString();
    } catch (Exception e) {
        // ignore access or connection open errors
    }
    return null;
}
 
Example 21
Project: lams   File: StandardServer.java   Source Code and License 5 votes vote down vote up
public ObjectName preRegister(MBeanServer server,
                              ObjectName name) throws Exception {
    oname=name;
    mserver=server;
    domain=name.getDomain();
    return name;
}
 
Example 22
Project: lazycat   File: StatusTransformer.java   Source Code and License 5 votes vote down vote up
/**
 * Write detailed information about a manager.
 */
public static void writeManager(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode)
		throws Exception {

	if (mode == 0) {
		writer.print("<br>");
		writer.print(" Active sessions: ");
		writer.print(mBeanServer.getAttribute(objectName, "activeSessions"));
		writer.print(" Session count: ");
		writer.print(mBeanServer.getAttribute(objectName, "sessionCounter"));
		writer.print(" Max active sessions: ");
		writer.print(mBeanServer.getAttribute(objectName, "maxActive"));
		writer.print(" Rejected session creations: ");
		writer.print(mBeanServer.getAttribute(objectName, "rejectedSessions"));
		writer.print(" Expired sessions: ");
		writer.print(mBeanServer.getAttribute(objectName, "expiredSessions"));
		writer.print(" Longest session alive time: ");
		writer.print(formatSeconds(mBeanServer.getAttribute(objectName, "sessionMaxAliveTime")));
		writer.print(" Average session alive time: ");
		writer.print(formatSeconds(mBeanServer.getAttribute(objectName, "sessionAverageAliveTime")));
		writer.print(" Processing time: ");
		writer.print(formatTime(mBeanServer.getAttribute(objectName, "processingTime"), false));
	} else if (mode == 1) {
		// for now we don't write out the wrapper details
	}

}
 
Example 23
Project: jdk8u-jdk   File: AuthorizationTest.java   Source Code and License 5 votes vote down vote up
protected int doInvokeRequest(MBeanServerConnection mbsc,
                              ObjectName on,
                              boolean expectedException) {
    int errorCount = 0;

    try {
        Utils.debug(Utils.DEBUG_STANDARD,
            "ClientSide::doInvokeRequest: Invoke operations on the MBean") ;

        mbsc.invoke(on, "operation", null, null) ;

        if (expectedException) {
            System.out.println("ClientSide::doInvokeRequest: " +
                "(ERROR) Invoke did not fail with expected SecurityException");
            errorCount++;
        } else {
            System.out.println("ClientSide::doInvokeRequest: (OK) Invoke succeed") ;
        }
    } catch(Exception e) {
        Utils.printThrowable(e, true) ;
        if (expectedException) {
            if (e instanceof java.lang.SecurityException) {
                System.out.println("ClientSide::doInvokeRequest: " +
                    "(OK) Invoke failed with expected SecurityException") ;
            } else {
                System.out.println("ClientSide::doInvokeRequest: " +
                    " (ERROR) Invoke failed with " +
                    e.getClass() + " instead of expected SecurityException");
                errorCount++;
            }
        } else {
            System.out.println("ClientSide::doInvokeRequest: " +
                "(ERROR) Invoke failed");
            errorCount++;
        }
    }
    return errorCount;
}
 
Example 24
Project: openjdk-jdk10   File: RelationNotification.java   Source Code and License 5 votes vote down vote up
/**
 * Returns old value of updated role (only for role update).
 *
 * @return the old value of the updated role.
 */
public List<ObjectName> getOldRoleValue() {
    List<ObjectName> result;
    if (oldRoleValue != null) {
        result = new ArrayList<ObjectName>(oldRoleValue);
    } else {
        result = Collections.emptyList();
    }
    return result;
}
 
Example 25
Project: monarch   File: DistributedSystemBridge.java   Source Code and License 5 votes vote down vote up
/**
 * Removed the proxy from the map.
 *
 * @param objectName name of the proxy to be removed.
 * @param proxy actual reference to the proxy object
 * @return whether all proxies have been removed or not. In this case it will always be false.
 *         Kept it for consistency for MBeanAggregator.
 */
public boolean removeGatewaySenderFromSystem(ObjectName objectName, GatewaySenderMXBean proxy,
    FederationComponent oldState) {
  if (mapOfGatewaySenders != null) {
    mapOfGatewaySenders.remove(objectName);
    gatewaySenderSetSize = mapOfGatewaySenders.values().size();
    if (mapOfGatewaySenders.values().size() == 0) {
      gatewaySenderSetSize = 0;
      return true;

    }
  }
  updateGatewaySender(objectName, null, oldState);
  return false;
}
 
Example 26
Project: jdk8u-jdk   File: RMIConnector.java   Source Code and License 5 votes vote down vote up
public ObjectInstance createMBean(String className,
        ObjectName name,
        Object params[],
        String signature[])
        throws ReflectionException,
        InstanceAlreadyExistsException,
        MBeanRegistrationException,
        MBeanException,
        NotCompliantMBeanException,
        IOException {
    if (logger.debugOn())
        logger.debug("createMBean(String,ObjectName,Object[],String[])",
                "className=" + className + ", name="
                + name + ", signature=" + strings(signature));

    final MarshalledObject<Object[]> sParams =
            new MarshalledObject<Object[]>(params);
    final ClassLoader old = pushDefaultClassLoader();
    try {
        return connection.createMBean(className,
                name,
                sParams,
                signature,
                delegationSubject);
    } catch (IOException ioe) {
        communicatorAdmin.gotIOException(ioe);

        return connection.createMBean(className,
                name,
                sParams,
                signature,
                delegationSubject);
    } finally {
        popDefaultClassLoader(old);
    }
}
 
Example 27
Project: monarch   File: ShellCommandsController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, value = "/mbean/query")
public ResponseEntity<?> queryNames(@RequestBody final QueryParameterSource query) {
  try {
    final Set<ObjectName> objectNames =
        getMBeanServer().queryNames(query.getObjectName(), query.getQueryExpression());

    return new ResponseEntity<byte[]>(IOUtils.serializeObject(objectNames), HttpStatus.OK);
  } catch (IOException e) {
    return new ResponseEntity<String>(printStackTrace(e), HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
 
Example 28
Project: lams   File: ContainerBase.java   Source Code and License 5 votes vote down vote up
public ObjectName[] getChildren() {
    ObjectName result[]=new ObjectName[children.size()];
    Iterator it=children.values().iterator();
    int i=0;
    while( it.hasNext() ) {
        Object next=it.next();
        if( next instanceof ContainerBase ) {
            result[i++]=((ContainerBase)next).getJmxName();
        }
    }
    return result;
}
 
Example 29
Project: monarch   File: MX4JModelMBean.java   Source Code and License 5 votes vote down vote up
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
  if (m_canBeRegistered) {
    m_mbeanServer = server;
    return name;
  } else {
    throw new MBeanRegistrationException(new IllegalStateException(
        LocalizedStrings.MX4JModelMBean_MODELMBEAN_CANNOT_BE_REGISTERED_UNTIL_SETMODELMBEANINFO_HAS_BEEN_CALLED
            .toLocalizedString()));
  }
}
 
Example 30
Project: monarch   File: MonitoringRegionCacheListener.java   Source Code and License 5 votes vote down vote up
@Override
public void afterUpdate(EntryEvent<String, Object> event) {
  ObjectName objectName = null;
  try {

    if (!service.isStartedAndOpen() || !service.isManager()) {
      // NO OP return; No work for Non Manager Nodes
      return;
    }
    objectName = ObjectName.getInstance(event.getKey());

    FederationComponent oldObject = (FederationComponent) event.getOldValue();
    FederationComponent newObject = (FederationComponent) event.getNewValue();
    String className = newObject.getMBeanInterfaceClass();
    Class interfaceClass;
    if (classRef.get(className) != null) {
      interfaceClass = classRef.get(className);
    } else {
      interfaceClass = ClassLoadUtil.classFromName(className);
      classRef.put(className, interfaceClass);
    }

    service.afterUpdateProxy(objectName, interfaceClass, null, newObject, oldObject);

  } catch (Exception e) {
    if (logger.isDebugEnabled()) {
      logger.debug("Aggregation Failed failed for {} with exception {}", e);
    }
  }

}
 
Example 31
Project: OpenJSharp   File: JvmMemMgrPoolRelTableMeta.java   Source Code and License 5 votes vote down vote up
public synchronized void addEntry(SnmpOid rowOid, ObjectName objname,
             Object entry)
    throws SnmpStatusException {
    if (! (entry instanceof JvmMemMgrPoolRelEntryMBean) )
        throw new ClassCastException("Entries for Table \"" +
                       "JvmMemMgrPoolRelTable" + "\" must implement the \"" +
                       "JvmMemMgrPoolRelEntryMBean" + "\" interface.");
    super.addEntry(rowOid, objname, entry);
}
 
Example 32
Project: Byter   File: JmxUtils.java   Source Code and License 5 votes vote down vote up
/**
 * creates a ObjectName with specific packagename and type.
 * @param packageName desired packageName
 * @param type desired type
 * @param concatRandomInt concat a int at the type
 * @return null(default) | instanced ObjectName
 */
public static ObjectName objectName(final String packageName, final String type, final boolean concatRandomInt){
    try{
        if(!concatRandomInt)
            return new ObjectName( packageName+":type="+type);
        else{
            writerId++;
            return new ObjectName( packageName+":type="+type+"-id-"+writerId);
        }
    } catch (MalformedObjectNameException e) {
        log.log(Level.WARNING, "ObjectName is malformed!");
        return null;
    }
}
 
Example 33
Project: Pogamut3   File: PogamutJMX.java   Source Code and License 5 votes vote down vote up
/**
 * Creates hierarchical ObjectNames given a parent and name of the MBean.
 * Extra elements can be inserted into the path through typeExtra param.
 * 
 * @param parent 
 *            parent's ObjectName
 * @param childName
 *            name of this object, if null no name element will be appended
 * @return ObjectName of form: domain=[parent's domain],type=[parent's
 *         type].[parent's name],name=[name]
 * @throws PogamutJMXNameException
 */
public static ObjectName getObjectName(ObjectName parent, String childName) throws PogamutJMXNameException {
	NullCheck.check(parent, "parent");
	NullCheck.check(childName, "childName");
	
	String parentDomain = parent.getKeyProperty("domain");
	String parentType = parent.getKeyProperty("type");
	String parentName = parent.getKeyProperty("name");
	
	String childType = parentType + "." + parentName;
	
	return getObjectName(parentDomain, childType, childName);		
}
 
Example 34
Project: tomcat7   File: StatusTransformer.java   Source Code and License 5 votes vote down vote up
/**
 * Write JSP monitoring information.
 */
public static void writeJspMonitor(PrintWriter writer,
                                   Set<ObjectName> jspMonitorONs,
                                   MBeanServer mBeanServer,
                                   int mode)
        throws Exception {

    int jspCount = 0;
    int jspReloadCount = 0;

    Iterator<ObjectName> iter = jspMonitorONs.iterator();
    while (iter.hasNext()) {
        ObjectName jspMonitorON = iter.next();
        Object obj = mBeanServer.getAttribute(jspMonitorON, "jspCount");
        jspCount += ((Integer) obj).intValue();
        obj = mBeanServer.getAttribute(jspMonitorON, "jspReloadCount");
        jspReloadCount += ((Integer) obj).intValue();
    }

    if (mode == 0) {
        writer.print("<br>");
        writer.print(" JSPs loaded: ");
        writer.print(jspCount);
        writer.print(" JSPs reloaded: ");
        writer.print(jspReloadCount);
    } else if (mode == 1) {
        // for now we don't write out anything
    }
}
 
Example 35
Project: jdk8u-jdk   File: SystemClassLoaderTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    ClassLoader mbsClassLoader = mbs.getClass().getClassLoader();

    String testClassName = Test.class.getName();

    // Check that the MBeanServer class loader does not know our test class
    try {
        Class.forName(testClassName, true, mbsClassLoader);
        System.out.println("TEST IS INVALID: MBEANSERVER'S CLASS LOADER " +
                           "KNOWS OUR TEST CLASS");
        System.exit(1);
    } catch (ClassNotFoundException e) {
        // As required
    }

    // Register the MBean
    //
    System.out.println("Create MBean from this class");
    ObjectName objectName = new ObjectName("whatever:type=whatever");
    mbs.createMBean(testClassName, objectName);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example 36
Project: hashsdn-controller   File: ConfigRegistryImplLookupTest.java   Source Code and License 5 votes vote down vote up
private static void registerRuntimeBean(final RuntimeBean object, final BaseJMXRegistrator baseJMXRegistrator,
        final ObjectName runtimeON) throws InstanceAlreadyExistsException {
    String factoryName = ObjectNameUtil.getFactoryName(runtimeON);
    String instanceName = ObjectNameUtil.getInstanceName(runtimeON);
    Map<String, String> properties = ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(runtimeON);

    RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
            .createRuntimeBeanRegistrator(new ModuleIdentifier(factoryName, instanceName));

    assertThat(properties.isEmpty(), is(true));

    runtimeBeanRegistrator.registerRoot(object);
}
 
Example 37
Project: Pogamut3   File: PogamutMBeanServer.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized void addNotificationListener(ObjectName name, ObjectName listener,
		NotificationFilter filter, Object handback)
		throws InstanceNotFoundException {
	mbs.addNotificationListener(name, listener, filter, handback);
	Listener1 l = new Listener1(name, listener, filter, handback);
	listeners.add(l);
	listeners1.add(l);
}
 
Example 38
Project: Pogamut3   File: PogamutMBeanServer.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized ObjectInstance createMBean(String className, ObjectName name)
		throws ReflectionException, InstanceAlreadyExistsException,
		MBeanRegistrationException, MBeanException,
		NotCompliantMBeanException {
	throw new UnsupportedOperationException("Not supported by PogamutMBeanServer yet...");
}
 
Example 39
Project: Pogamut3   File: PogamutMBeanServer.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized ObjectInstance createMBean(String className, ObjectName name,
		ObjectName loaderName) throws ReflectionException,
		InstanceAlreadyExistsException, MBeanRegistrationException,
		MBeanException, NotCompliantMBeanException,
		InstanceNotFoundException {
	throw new UnsupportedOperationException("Not supported by PogamutMBeanServer yet...");
}
 
Example 40
Project: jdk8u-jdk   File: ScanManager.java   Source Code and License 5 votes vote down vote up
public Map<String,DirectoryScannerMXBean> getDirectoryScanners() {
    final Map<String,DirectoryScannerMXBean> proxyMap = newHashMap();
    for (Entry<ObjectName,DirectoryScannerMXBean> item : scanmap.entrySet()){
        proxyMap.put(item.getKey().getKeyProperty("name"),item.getValue());
    }
    return proxyMap;
}
 
Example 41
Project: jdk8u-jdk   File: AnnotationTest.java   Source Code and License 5 votes vote down vote up
private static void check(MBeanServer mbs, ObjectName on) throws Exception {
    MBeanInfo mbi = mbs.getMBeanInfo(on);

    // check the MBean itself
    check(mbi);

    // check attributes
    MBeanAttributeInfo[] attrs = mbi.getAttributes();
    for (MBeanAttributeInfo attr : attrs) {
        check(attr);
        if (attr.getName().equals("ReadOnly"))
            check("@Full", attr.getDescriptor(), expectedFullDescriptor);
    }

    // check operations
    MBeanOperationInfo[] ops = mbi.getOperations();
    for (MBeanOperationInfo op : ops) {
        check(op);
        check(op.getSignature());
    }

    MBeanConstructorInfo[] constrs = mbi.getConstructors();
    for (MBeanConstructorInfo constr : constrs) {
        check(constr);
        check(constr.getSignature());
    }
}
 
Example 42
Project: tomcat7   File: NamingContextListener.java   Source Code and License 5 votes vote down vote up
/**
 * Set the specified resources in the naming context.
 */
public void removeResource(String name) {

    try {
        envCtx.unbind(name);
    } catch (NamingException e) {
        logger.error(sm.getString("naming.unbindFailed", e));
    }

    ObjectName on = objectNames.get(name);
    if (on != null) {
        Registry.getRegistry(null, null).unregisterComponent(on);
    }

}
 
Example 43
Project: OpenJSharp   File: DefaultMBeanServerInterceptor.java   Source Code and License 5 votes vote down vote up
/**
 * Removes a MBean in the repository,
 * sends MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
 * returns ResourceContext for special resources such as ClassLoaders
 * or JMXNamespaces, or null. For regular MBean this method returns
 * ResourceContext.NONE.
 *
 * @return a ResourceContext for special resources such as ClassLoaders
 *         or JMXNamespaces.
 */
private ResourceContext unregisterFromRepository(
        final Object resource,
        final DynamicMBean object,
        final ObjectName logicalName)
        throws InstanceNotFoundException {

    // Creates a registration context, if needed.
    //
    final ResourceContext context =
            makeResourceContextFor(resource, logicalName);


    repository.remove(logicalName, context);

    // ---------------------
    // Send deletion event
    // ---------------------
    if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
        MBEANSERVER_LOGGER.logp(Level.FINER,
                DefaultMBeanServerInterceptor.class.getName(),
                "unregisterMBean", "Send delete notification of object " +
                logicalName.getCanonicalName());
    }

    sendNotification(MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
            logicalName);
    return context;
}
 
Example 44
Project: openjdk-jdk10   File: DefaultMBeanServerInterceptor.java   Source Code and License 5 votes vote down vote up
/**
 * Unregisters a ClassLoader from the CLR.
 * This method is called by the ResourceContext from within the
 * repository lock.
 * @param loader       The ClassLoader.
 * @param logicalName  The ClassLoader MBean ObjectName.
 */
private void removeClassLoader(ClassLoader loader,
        final ObjectName logicalName) {
    /**
     * Removes the  MBean from the default loader repository.
     */
    if (loader != server.getClass().getClassLoader()) {
        final ModifiableClassLoaderRepository clr = getInstantiatorCLR();
        if (clr != null) {
            clr.removeClassLoader(logicalName);
        }
    }
}
 
Example 45
Project: Pogamut3   File: PogamutMBeanServer.java   Source Code and License 5 votes vote down vote up
@Override
public Object invoke(ObjectName name, String operationName,
		Object[] params, String[] signature)
		throws InstanceNotFoundException, MBeanException,
		ReflectionException {
	return mbs.invoke(name, operationName, params, signature);
}
 
Example 46
Project: OpenJSharp   File: DefaultMBeanServerInterceptor.java   Source Code and License 5 votes vote down vote up
public void addNotificationListener(ObjectName name,
                                    ObjectName listener,
                                    NotificationFilter filter,
                                    Object handback)
        throws InstanceNotFoundException {

    // ------------------------------
    // ------------------------------

    // ----------------
    // Get listener object
    // ----------------
    DynamicMBean instance = getMBean(listener);
    Object resource = getResource(instance);
    if (!(resource instanceof NotificationListener)) {
        throw new RuntimeOperationsException(new
            IllegalArgumentException(listener.getCanonicalName()),
            "The MBean " + listener.getCanonicalName() +
            "does not implement the NotificationListener interface") ;
    }

    // ----------------
    // Add a listener on an MBean
    // ----------------
    if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
        MBEANSERVER_LOGGER.logp(Level.FINER,
                DefaultMBeanServerInterceptor.class.getName(),
                "addNotificationListener",
                "ObjectName = " + name + ", Listener = " + listener);
    }
    server.addNotificationListener(name,(NotificationListener) resource,
                                   filter, handback) ;
}
 
Example 47
Project: hashsdn-controller   File: ServiceReferenceRegistryImpl.java   Source Code and License 5 votes vote down vote up
private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set<String> names)
        throws InstanceNotFoundException {
    ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE);
    assertWritable();
    Set<ServiceReference> serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, names);
    for (ServiceReference sr : serviceReferencesLinkingTo) {
        removeServiceReference(sr);
    }
    return !serviceReferencesLinkingTo.isEmpty();
}
 
Example 48
Project: apache-tomcat-7.0.73-with-comment   File: NamingContextListener.java   Source Code and License 5 votes vote down vote up
/**
 * Set the specified resources in the naming context.
 */
public void removeResource(String name) {

    try {
        envCtx.unbind(name);
    } catch (NamingException e) {
        logger.error(sm.getString("naming.unbindFailed", e));
    }

    ObjectName on = objectNames.get(name);
    if (on != null) {
        Registry.getRegistry(null, null).unregisterComponent(on);
    }

}
 
Example 49
Project: openjdk-jdk10   File: ArrayNotificationBuffer.java   Source Code and License 5 votes vote down vote up
private void createListeners() {
    logger.debug("createListeners", "starts");

    synchronized (this) {
        createdDuringQuery = new HashSet<ObjectName>();
    }

    try {
        addNotificationListener(MBeanServerDelegate.DELEGATE_NAME,
                                creationListener, creationFilter, null);
        logger.debug("createListeners", "added creationListener");
    } catch (Exception e) {
        final String msg = "Can't add listener to MBean server delegate: ";
        RuntimeException re = new IllegalArgumentException(msg + e);
        EnvHelp.initCause(re, e);
        logger.fine("createListeners", msg + e);
        logger.debug("createListeners", e);
        throw re;
    }

    /* Spec doesn't say whether Set returned by QueryNames can be modified
       so we clone it. */
    Set<ObjectName> names = queryNames(null, broadcasterQuery);
    names = new HashSet<ObjectName>(names);

    synchronized (this) {
        names.addAll(createdDuringQuery);
        createdDuringQuery = null;
    }

    for (ObjectName name : names)
        addBufferListener(name);
    logger.debug("createListeners", "ends");
}
 
Example 50
Project: openjdk-jdk10   File: NotificationBufferTest.java   Source Code and License 5 votes vote down vote up
private static NotificationBufferFilter makeFilter(final Integer id,
                                                   final ObjectName pattern,
                                                   final NotificationFilter filter) {
    return new NotificationBufferFilter() {
        public void apply(List<TargetedNotification> notifs,
                          ObjectName source, Notification notif) {
            if (pattern.apply(source)) {
                if (filter == null || filter.isNotificationEnabled(notif))
                    notifs.add(new TargetedNotification(notif, id));
            }
        }
    };
}
 
Example 51
Project: monarch   File: DistributedRegionBridge.java   Source Code and License 5 votes vote down vote up
/**
 * @return set of member ids on which this region is present.
 */
public String[] getMembers() {
  Iterator<ObjectName> it = mapOfProxy.keySet().iterator();
  if (it != null) {
    List<String> memberList = new ArrayList<String>();
    while (it.hasNext()) {
      ObjectName tempObjName = it.next();
      String formatedMemberId = (String) tempObjName.getKeyProperty("member");
      memberList.add(formatedMemberId);
    }
    String[] members = new String[memberList.size()];
    return memberList.toArray(members);
  }
  return ManagementConstants.NO_DATA_STRING;
}
 
Example 52
Project: monarch   File: SystemManagementService.java   Source Code and License 5 votes vote down vote up
public boolean afterCreateProxy(ObjectName objectName, Class interfaceClass, Object proxyObject,
    FederationComponent newVal) {
  for (ProxyListener listener : proxyListeners) {
    listener.afterCreateProxy(objectName, interfaceClass, proxyObject, newVal);
  }
  return true;
}
 
Example 53
Project: monarch   File: LocalProcessControllerJUnitTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  pid = ProcessUtils.identifyPid();
  final Process process = new Process(pid, true);

  this.objectName = ObjectName
      .getInstance(getClass().getSimpleName() + ":testName=" + testName.getMethodName());
  this.server = ManagementFactory.getPlatformMBeanServer();

  final ObjectInstance instance = this.server.registerMBean(process, objectName);
  assertNotNull(instance);
}
 
Example 54
Project: OpenJSharp   File: MBeanServerAccessController.java   Source Code and License 5 votes vote down vote up
/**
 * Call <code>checkRead()</code>, then forward this method to the
 * wrapped object.
 */
public void removeNotificationListener(ObjectName name,
                                       NotificationListener listener,
                                       NotificationFilter filter,
                                       Object handback)
    throws InstanceNotFoundException, ListenerNotFoundException {
    checkRead();
    getMBeanServer().removeNotificationListener(name, listener,
                                                filter, handback);
}
 
Example 55
Project: Pogamut3   File: AbstractJMXAgentObserver.java   Source Code and License 5 votes vote down vote up
/**
 * Creates JMX wrapper for agent on specified adress and adds it to the list
 * of all connected agents.
 * @param serviceUrl URL of the JMX service where remote agent resides eg. service:jmx:rmi:///jndi/rmi://localhost:9999/server
 * @param objectName name of the MBean representing agent eg. myDomain:name=MyAgent1
 */
protected void addJMXAgentFromAdress(String serviceUrl, ObjectName objectName) throws IOException {
    JMXServiceURL url = new JMXServiceURL(serviceUrl);
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    
    IAgent agent = JMX.newMXBeanProxy(mbsc, objectName, IAgent.class);
    
    agents.add(agent);
}
 
Example 56
Project: OpenJSharp   File: DefaultMBeanServerInterceptor.java   Source Code and License 5 votes vote down vote up
private Set<ObjectInstance> queryMBeansImpl(ObjectName name,
                                            QueryExp query) {
    // Query the MBeans on the repository
    //
    Set<NamedObject> list = repository.query(name, query);

    return (objectInstancesFromFilteredNamedObjects(list, query));
}
 
Example 57
Project: hashsdn-controller   File: BlueprintContainerRestartServiceImpl.java   Source Code and License 5 votes vote down vote up
private void restartConfigModules(final List<Entry<String, ModuleIdentifier>> configModules,
        final ConfigSubsystemFacade configFacade) throws ParserConfigurationException, DocumentedException,
                ValidationException, ConflictingVersionException {

    Document document = XmlUtil.newDocument();
    Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
    Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY,
            Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
    dataElement.appendChild(modulesElement);

    Config configMapping = configFacade.getConfigMapping();

    ConfigRegistry configRegistryClient = new ConfigRegistryJMXClient(ManagementFactory.getPlatformMBeanServer());
    for (Entry<String, ModuleIdentifier> entry : configModules) {
        String moduleNamespace = entry.getKey();
        ModuleIdentifier moduleId = entry.getValue();
        try {
            ObjectName instanceON = configRegistryClient.lookupConfigBean(moduleId.getFactoryName(),
                    moduleId.getInstanceName());

            LOG.debug("Found config module instance ObjectName: {}", instanceON);

            Element moduleElement = configMapping.moduleToXml(moduleNamespace, moduleId.getFactoryName(),
                    moduleId.getInstanceName(), instanceON, document);
            modulesElement.appendChild(moduleElement);
        } catch (final InstanceNotFoundException e) {
            LOG.warn("Error looking up config module: namespace {}, module name {}, instance {}",
                    moduleNamespace, moduleId.getFactoryName(), moduleId.getInstanceName(), e);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Pushing config xml: {}", XmlUtil.toString(dataElement));
    }

    ConfigExecution execution = new ConfigExecution(configMapping, XmlElement.fromDomElement(dataElement),
            TestOption.testThenSet, EditStrategyType.recreate);
    configFacade.executeConfigExecution(execution);
    configFacade.commitSilentTransaction();
}
 
Example 58
Project: openjdk-jdk10   File: SecurityTest.java   Source Code and License 4 votes vote down vote up
private void doRequests() throws Exception {

            // Send  some requests to the remote JMX server
            ObjectName objName1 =
                new ObjectName("TestDomain:class=MBS_Light,rank=1");
            String mbeanClass = "MBS_Light";
            Exception exception = new Exception("MY TEST EXCEPTION");
            Attribute attException = new Attribute("AnException", exception);
            Error error = new Error("MY TEST ERROR");
            Attribute attError = new Attribute("AnError", error);
            String opParamString = "TOTORO";
            RjmxMBeanParameter opParam = new RjmxMBeanParameter(opParamString);
            Object[] params1 = {opParamString};
            String[] sig1 = {"java.lang.String"};
            Object[] params2 = {opParam};
            String[] sig2 = {"RjmxMBeanParameter"};

            // Create and register the MBean
            Utils.debug(Utils.DEBUG_STANDARD,
                "ClientSide::doRequests: Create and register the MBean");
            mbsc.createMBean(mbeanClass, objName1);
            if (!mbsc.isRegistered(objName1)) {
                throw new Exception("Unable to register an MBean");
            }

            // Set attributes of the MBean
            Utils.debug(Utils.DEBUG_STANDARD,
                "ClientSide::doRequests: Set attributes of the MBean");
            mbsc.setAttribute(objName1, attException);
            mbsc.setAttribute(objName1, attError);

            // Get attributes of the MBean
            Utils.debug(Utils.DEBUG_STANDARD,
                "ClientSide::doRequests: Get attributes of the MBean");
            Exception retException =
                (Exception) mbsc.getAttribute(objName1,"AnException");
            if (!retException.getMessage().equals(exception.getMessage())) {
                System.out.println("Expected = " + exception);
                System.out.println("Got = " + retException);
                throw new Exception("Attribute AnException not as expected");
            }
            Error retError = (Error) mbsc.getAttribute(objName1, "AnError");
            if (!retError.getMessage().equals(error.getMessage())) {
                System.out.println("Expected = " + error);
                System.out.println("Got = " + retError);
                throw new Exception("Attribute AnError not as expected");
            }

            // Invoke operations on the MBean
            Utils.debug(Utils.DEBUG_STANDARD,
                "ClientSide::doRequests: Invoke operations on the MBean");
            RjmxMBeanParameter res1 =
                (RjmxMBeanParameter) mbsc.invoke(objName1, "operate1", params1, sig1);
            if (!res1.equals(opParam)) {
                System.out.println("Expected = " + opParam);
                System.out.println("Got = " + res1);
                throw new Exception("Operation operate1 behaved badly");
            }
            String res2 =
                (String) mbsc.invoke(objName1, "operate2", params2, sig2);
            if (!res2.equals(opParamString)) {
                System.out.println("Expected = " + opParamString);
                System.out.println("Got = " + res2);
                throw new Exception("Operation operate2 behaved badly");
            }

            // Unregister the MBean
            Utils.debug(Utils.DEBUG_STANDARD,
                "ClientSide::doRequests: Unregister the MBean");
            mbsc.unregisterMBean(objName1);
            if (mbsc.isRegistered(objName1)) {
                throw new Exception("Unable to unregister an MBean");
            }
        }
 
Example 59
Project: monarch   File: MBeanJMXAdapter.java   Source Code and License 4 votes vote down vote up
public static ObjectName getAsycnEventQueueMBeanName(String member, String queueId) {
  return getObjectName((MessageFormat.format(OBJECTNAME__ASYNCEVENTQUEUE_MXBEAN,
      new Object[] {queueId, makeCompliantName(member)})));
}
 
Example 60
Project: hashsdn-controller   File: JMXNotifierConfigRegistry.java   Source Code and License 4 votes vote down vote up
@Override
public List<ObjectName> getOpenConfigs() {
    return delegate.getOpenConfigs();
}