Search in sources :

Example 96 with ObjectInstance

use of javax.management.ObjectInstance in project lucene-solr by apache.

the class TestJmxIntegration method testJmxOnCoreReload.

@Test
@Ignore("timing problem? https://issues.apache.org/jira/browse/SOLR-2715")
public void testJmxOnCoreReload() throws Exception {
    String coreName = h.getCore().getName();
    Set<ObjectInstance> oldBeans = mbeanServer.queryMBeans(null, null);
    int oldNumberOfObjects = 0;
    for (ObjectInstance bean : oldBeans) {
        try {
            if (String.valueOf(h.getCore().hashCode()).equals(mbeanServer.getAttribute(bean.getObjectName(), "coreHashCode"))) {
                oldNumberOfObjects++;
            }
        } catch (AttributeNotFoundException e) {
        // expected
        }
    }
    log.info("Before Reload: Size of infoRegistry: " + h.getCore().getInfoRegistry().size() + " MBeans: " + oldNumberOfObjects);
    assertEquals("Number of registered MBeans is not the same as info registry size", h.getCore().getInfoRegistry().size(), oldNumberOfObjects);
    h.getCoreContainer().reload(coreName);
    Set<ObjectInstance> newBeans = mbeanServer.queryMBeans(null, null);
    int newNumberOfObjects = 0;
    int registrySize = 0;
    try (SolrCore core = h.getCoreContainer().getCore(coreName)) {
        registrySize = core.getInfoRegistry().size();
        for (ObjectInstance bean : newBeans) {
            try {
                if (String.valueOf(core.hashCode()).equals(mbeanServer.getAttribute(bean.getObjectName(), "coreHashCode"))) {
                    newNumberOfObjects++;
                }
            } catch (AttributeNotFoundException e) {
            // expected
            }
        }
    }
    log.info("After Reload: Size of infoRegistry: " + registrySize + " MBeans: " + newNumberOfObjects);
    assertEquals("Number of registered MBeans is not the same as info registry size", registrySize, newNumberOfObjects);
}
Also used : AttributeNotFoundException(javax.management.AttributeNotFoundException) ObjectInstance(javax.management.ObjectInstance) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 97 with ObjectInstance

use of javax.management.ObjectInstance in project jdk8u_jdk by JetBrains.

the class LibraryLoaderTest method main.

public static void main(String[] args) throws Exception {
    String osName = System.getProperty("os.name");
    System.out.println("os.name=" + osName);
    String osArch = System.getProperty("os.arch");
    System.out.println("os.name=" + osArch);
    //
    if ((!(osName.equals("SunOS") && osArch.equals("sparc"))) && (!(osName.startsWith("Windows") && osArch.equals("x86")))) {
        System.out.println("This test runs only on Solaris/SPARC and Windows/x86 platforms");
        System.out.println("Bye! Bye!");
        return;
    }
    String libPath = System.getProperty("java.library.path");
    System.out.println("java.library.path=" + libPath);
    String testSrc = System.getProperty("test.src");
    System.out.println("test.src=" + testSrc);
    String workingDir = System.getProperty("user.dir");
    System.out.println("user.dir=" + workingDir);
    String urlCodebase;
    if (testSrc.startsWith("/")) {
        urlCodebase = "file:" + testSrc.replace(File.separatorChar, '/') + "/";
    } else {
        urlCodebase = "file:/" + testSrc.replace(File.separatorChar, '/') + "/";
    }
    // Create MBeanServer
    //
    MBeanServer server = MBeanServerFactory.newMBeanServer();
    //
    for (int i = 0; i < mletInfo.length; i++) {
        // Create ObjectName for MLet
        //
        ObjectName mlet = new ObjectName(mletInfo[i][0]);
        server.createMBean("javax.management.loading.MLet", mlet);
        System.out.println("MLet = " + mlet);
        // Display old library directory and set it to test.classes
        //
        String libraryDirectory = (String) server.getAttribute(mlet, "LibraryDirectory");
        System.out.println("Old Library Directory = " + libraryDirectory);
        Attribute attribute = new Attribute("LibraryDirectory", workingDir);
        server.setAttribute(mlet, attribute);
        libraryDirectory = (String) server.getAttribute(mlet, "LibraryDirectory");
        System.out.println("New Library Directory = " + libraryDirectory);
        // Get MBeans from URL
        //
        String mletURL = urlCodebase + mletInfo[i][1];
        System.out.println("MLet URL = " + mletURL);
        Object[] params = new Object[] { mletURL };
        String[] signature = new String[] { "java.lang.String" };
        Object[] res = ((Set<?>) server.invoke(mlet, "getMBeansFromURL", params, signature)).toArray();
        //
        for (int j = 0; j < res.length; j++) {
            //
            if (res[j] instanceof Throwable) {
                ((Throwable) res[j]).printStackTrace(System.out);
                throw new Exception("Failed to load the MBean #" + j, (Throwable) res[j]);
            }
            // On each of the loaded MBeans, try to invoke their
            // native operation
            //
            Object result = null;
            try {
                ObjectName mbean = ((ObjectInstance) res[j]).getObjectName();
                result = server.getAttribute(mbean, "Random");
                System.out.println("MBean #" + j + " = " + mbean);
                System.out.println("Random number = " + result);
            } catch (ReflectionException e) {
                e.getTargetException().printStackTrace(System.out);
                throw new Exception("A ReflectionException " + "occured when attempting to invoke " + "a native library based operation.", e.getTargetException());
            }
        }
    }
}
Also used : ReflectionException(javax.management.ReflectionException) Set(java.util.Set) Attribute(javax.management.Attribute) ObjectInstance(javax.management.ObjectInstance) ReflectionException(javax.management.ReflectionException) ObjectName(javax.management.ObjectName) MBeanServer(javax.management.MBeanServer)

Example 98 with ObjectInstance

use of javax.management.ObjectInstance in project jdk8u_jdk by JetBrains.

the class MLet method getMBeansFromURL.

/**
      * Loads a text file containing MLET tags that define the MBeans to
      * be added to the MBean server. The location of the text file is specified by
      * a URL. The MBeans specified in the MLET file will be instantiated and
      * registered in the MBean server.
      *
      * @param url The URL of the text file to be loaded as String object.
      *
      * @return A set containing one entry per MLET tag in the m-let
      * text file loaded.  Each entry specifies either the
      * ObjectInstance for the created MBean, or a throwable object
      * (that is, an error or an exception) if the MBean could not be
      * created.
      *
      * @exception ServiceNotFoundException One of the following
      * errors has occurred: The m-let text file does not contain an
      * MLET tag, the m-let text file is not found, a mandatory
      * attribute of the MLET tag is not specified, the url is
      * malformed.
      * @exception IllegalStateException MLet MBean is not registered
      * with an MBeanServer.
      *
      */
public Set<Object> getMBeansFromURL(String url) throws ServiceNotFoundException {
    String mth = "getMBeansFromURL";
    if (server == null) {
        throw new IllegalStateException("This MLet MBean is not " + "registered with an MBeanServer.");
    }
    // Parse arguments
    if (url == null) {
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "URL is null");
        throw new ServiceNotFoundException("The specified URL is null");
    } else {
        url = url.replace(File.separatorChar, '/');
    }
    if (MLET_LOGGER.isLoggable(Level.FINER)) {
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "<URL = " + url + ">");
    }
    // Parse URL
    try {
        MLetParser parser = new MLetParser();
        mletList = parser.parseURL(url);
    } catch (Exception e) {
        final String msg = "Problems while parsing URL [" + url + "], got exception [" + e.toString() + "]";
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
        throw EnvHelp.initCause(new ServiceNotFoundException(msg), e);
    }
    // Check that the list of MLets is not empty
    if (mletList.size() == 0) {
        final String msg = "File " + url + " not found or MLET tag not defined in file";
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
        throw new ServiceNotFoundException(msg);
    }
    // Walk through the list of MLets
    Set<Object> mbeans = new HashSet<Object>();
    for (MLetContent elmt : mletList) {
        // Initialize local variables
        String code = elmt.getCode();
        if (code != null) {
            if (code.endsWith(".class")) {
                code = code.substring(0, code.length() - 6);
            }
        }
        String name = elmt.getName();
        URL codebase = elmt.getCodeBase();
        String version = elmt.getVersion();
        String serName = elmt.getSerializedObject();
        String jarFiles = elmt.getJarFiles();
        URL documentBase = elmt.getDocumentBase();
        // Display debug information
        if (MLET_LOGGER.isLoggable(Level.FINER)) {
            final StringBuilder strb = new StringBuilder().append("\n\tMLET TAG     = ").append(elmt.getAttributes()).append("\n\tCODEBASE     = ").append(codebase).append("\n\tARCHIVE      = ").append(jarFiles).append("\n\tCODE         = ").append(code).append("\n\tOBJECT       = ").append(serName).append("\n\tNAME         = ").append(name).append("\n\tVERSION      = ").append(version).append("\n\tDOCUMENT URL = ").append(documentBase);
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, strb.toString());
        }
        // Load classes from JAR files
        StringTokenizer st = new StringTokenizer(jarFiles, ",", false);
        while (st.hasMoreTokens()) {
            String tok = st.nextToken().trim();
            if (MLET_LOGGER.isLoggable(Level.FINER)) {
                MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Load archive for codebase <" + codebase + ">, file <" + tok + ">");
            }
            //
            try {
                codebase = check(version, codebase, tok, elmt);
            } catch (Exception ex) {
                MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), mth, "Got unexpected exception", ex);
                mbeans.add(ex);
                continue;
            }
            // URLs to search for classes and resources.
            try {
                if (!Arrays.asList(getURLs()).contains(new URL(codebase.toString() + tok))) {
                    addURL(codebase + tok);
                }
            } catch (MalformedURLException me) {
            // OK : Ignore jar file if its name provokes the
            // URL to be an invalid one.
            }
        }
        // Instantiate the class specified in the
        // CODE or OBJECT section of the MLet tag
        //
        Object o;
        ObjectInstance objInst;
        if (code != null && serName != null) {
            final String msg = "CODE and OBJECT parameters cannot be specified at the " + "same time in tag MLET";
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
            mbeans.add(new Error(msg));
            continue;
        }
        if (code == null && serName == null) {
            final String msg = "Either CODE or OBJECT parameter must be specified in " + "tag MLET";
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
            mbeans.add(new Error(msg));
            continue;
        }
        try {
            if (code != null) {
                List<String> signat = elmt.getParameterTypes();
                List<String> stringPars = elmt.getParameterValues();
                List<Object> objectPars = new ArrayList<Object>();
                for (int i = 0; i < signat.size(); i++) {
                    objectPars.add(constructParameter(stringPars.get(i), signat.get(i)));
                }
                if (signat.isEmpty()) {
                    if (name == null) {
                        objInst = server.createMBean(code, null, mletObjectName);
                    } else {
                        objInst = server.createMBean(code, new ObjectName(name), mletObjectName);
                    }
                } else {
                    Object[] parms = objectPars.toArray();
                    String[] signature = new String[signat.size()];
                    signat.toArray(signature);
                    if (MLET_LOGGER.isLoggable(Level.FINEST)) {
                        final StringBuilder strb = new StringBuilder();
                        for (int i = 0; i < signature.length; i++) {
                            strb.append("\n\tSignature     = ").append(signature[i]).append("\t\nParams        = ").append(parms[i]);
                        }
                        MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), mth, strb.toString());
                    }
                    if (name == null) {
                        objInst = server.createMBean(code, null, mletObjectName, parms, signature);
                    } else {
                        objInst = server.createMBean(code, new ObjectName(name), mletObjectName, parms, signature);
                    }
                }
            } else {
                o = loadSerializedObject(codebase, serName);
                if (name == null) {
                    server.registerMBean(o, null);
                } else {
                    server.registerMBean(o, new ObjectName(name));
                }
                objInst = new ObjectInstance(name, o.getClass().getName());
            }
        } catch (ReflectionException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "ReflectionException", ex);
            mbeans.add(ex);
            continue;
        } catch (InstanceAlreadyExistsException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "InstanceAlreadyExistsException", ex);
            mbeans.add(ex);
            continue;
        } catch (MBeanRegistrationException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "MBeanRegistrationException", ex);
            mbeans.add(ex);
            continue;
        } catch (MBeanException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "MBeanException", ex);
            mbeans.add(ex);
            continue;
        } catch (NotCompliantMBeanException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "NotCompliantMBeanException", ex);
            mbeans.add(ex);
            continue;
        } catch (InstanceNotFoundException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "InstanceNotFoundException", ex);
            mbeans.add(ex);
            continue;
        } catch (IOException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "IOException", ex);
            mbeans.add(ex);
            continue;
        } catch (SecurityException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "SecurityException", ex);
            mbeans.add(ex);
            continue;
        } catch (Exception ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Exception", ex);
            mbeans.add(ex);
            continue;
        } catch (Error ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Error", ex);
            mbeans.add(ex);
            continue;
        }
        mbeans.add(objInst);
    }
    return mbeans;
}
Also used : MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) URL(java.net.URL) HashSet(java.util.HashSet) ReflectionException(javax.management.ReflectionException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ObjectInstance(javax.management.ObjectInstance) IOException(java.io.IOException) ServiceNotFoundException(javax.management.ServiceNotFoundException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ReflectionException(javax.management.ReflectionException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MBeanException(javax.management.MBeanException) ObjectName(javax.management.ObjectName) StringTokenizer(java.util.StringTokenizer) ServiceNotFoundException(javax.management.ServiceNotFoundException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) MBeanException(javax.management.MBeanException) MBeanRegistrationException(javax.management.MBeanRegistrationException)

Example 99 with ObjectInstance

use of javax.management.ObjectInstance in project jdk8u_jdk by JetBrains.

the class ServerNotifForwarder method checkMBeanPermission.

static void checkMBeanPermission(final MBeanServer mbs, final ObjectName name, final String actions) throws InstanceNotFoundException, SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        AccessControlContext acc = AccessController.getContext();
        ObjectInstance oi;
        try {
            oi = AccessController.doPrivileged(new PrivilegedExceptionAction<ObjectInstance>() {

                public ObjectInstance run() throws InstanceNotFoundException {
                    return mbs.getObjectInstance(name);
                }
            });
        } catch (PrivilegedActionException e) {
            throw (InstanceNotFoundException) extractException(e);
        }
        String classname = oi.getClassName();
        MBeanPermission perm = new MBeanPermission(classname, null, name, actions);
        sm.checkPermission(perm, acc);
    }
}
Also used : AccessControlContext(java.security.AccessControlContext) PrivilegedActionException(java.security.PrivilegedActionException) MBeanPermission(javax.management.MBeanPermission) ObjectInstance(javax.management.ObjectInstance) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction)

Example 100 with ObjectInstance

use of javax.management.ObjectInstance in project felix by apache.

the class MX4JMBeanServer method registerImpl.

private void registerImpl(MBeanMetaData metadata, boolean privileged) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
    introspector.introspect(metadata);
    if (!introspector.isMBeanCompliant(metadata))
        throw new NotCompliantMBeanException("MBean is not compliant");
    MBeanServerInterceptor head = getHeadInterceptor();
    try {
        // With this call, the MBean implementor can replace the ObjectName with a subclass that is not secure, secure it again
        head.registration(metadata, MBeanServerInterceptor.PRE_REGISTER);
        metadata.name = secureObjectName(metadata.name);
        metadata.instance = new ObjectInstance(metadata.name, metadata.info.getClassName());
        register(metadata, privileged);
        head.registration(metadata, MBeanServerInterceptor.POST_REGISTER_TRUE);
    } catch (Throwable x) {
        try {
            head.registration(metadata, MBeanServerInterceptor.POST_REGISTER_FALSE);
        } catch (MBeanRegistrationException ignored) {
        /* Ignore this one to rethrow the other one */
        }
        if (x instanceof SecurityException) {
            throw (SecurityException) x;
        } else if (x instanceof InstanceAlreadyExistsException) {
            throw (InstanceAlreadyExistsException) x;
        } else if (x instanceof MBeanRegistrationException) {
            throw (MBeanRegistrationException) x;
        } else if (x instanceof RuntimeOperationsException) {
            throw (RuntimeOperationsException) x;
        } else if (x instanceof JMRuntimeException) {
            throw (JMRuntimeException) x;
        } else if (x instanceof Exception) {
            throw new MBeanRegistrationException((Exception) x);
        } else if (x instanceof Error) {
            throw new MBeanRegistrationException(new RuntimeErrorException((Error) x));
        } else {
            throw new ImplementationException();
        }
    }
    if (metadata.mbean instanceof ClassLoader && !(metadata.mbean instanceof PrivateClassLoader)) {
        ClassLoader cl = (ClassLoader) metadata.mbean;
        getModifiableClassLoaderRepository().addClassLoader(cl);
    }
}
Also used : RuntimeErrorException(javax.management.RuntimeErrorException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) ImplementationException(org.apache.felix.mosgi.jmx.agent.mx4j.ImplementationException) ObjectInstance(javax.management.ObjectInstance) PrivateClassLoader(javax.management.loading.PrivateClassLoader) IntrospectionException(javax.management.IntrospectionException) OperationsException(javax.management.OperationsException) BadBinaryOpValueExpException(javax.management.BadBinaryOpValueExpException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) BadStringOperationException(javax.management.BadStringOperationException) ReflectionException(javax.management.ReflectionException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) RuntimeErrorException(javax.management.RuntimeErrorException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ListenerNotFoundException(javax.management.ListenerNotFoundException) RuntimeOperationsException(javax.management.RuntimeOperationsException) AttributeNotFoundException(javax.management.AttributeNotFoundException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) JMRuntimeException(javax.management.JMRuntimeException) PrivilegedActionException(java.security.PrivilegedActionException) BadAttributeValueExpException(javax.management.BadAttributeValueExpException) IOException(java.io.IOException) ImplementationException(org.apache.felix.mosgi.jmx.agent.mx4j.ImplementationException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) MBeanException(javax.management.MBeanException) InvalidApplicationException(javax.management.InvalidApplicationException) MBeanServerInterceptor(org.apache.felix.mosgi.jmx.agent.mx4j.server.interceptor.MBeanServerInterceptor) InvokerMBeanServerInterceptor(org.apache.felix.mosgi.jmx.agent.mx4j.server.interceptor.InvokerMBeanServerInterceptor) PrivateClassLoader(javax.management.loading.PrivateClassLoader) JMRuntimeException(javax.management.JMRuntimeException) MBeanRegistrationException(javax.management.MBeanRegistrationException) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Aggregations

ObjectInstance (javax.management.ObjectInstance)172 ObjectName (javax.management.ObjectName)102 Test (org.junit.Test)38 MBeanServer (javax.management.MBeanServer)36 InstanceNotFoundException (javax.management.InstanceNotFoundException)28 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)16 MBeanInfo (javax.management.MBeanInfo)16 InstanceAlreadyExistsException (javax.management.InstanceAlreadyExistsException)15 MBeanAttributeInfo (javax.management.MBeanAttributeInfo)15 HashMap (java.util.HashMap)13 Attribute (javax.management.Attribute)13 HashSet (java.util.HashSet)12 JmxResultProcessor (com.googlecode.jmxtrans.model.JmxResultProcessor)11 Result (com.googlecode.jmxtrans.model.Result)11 Set (java.util.Set)11 ReflectionException (javax.management.ReflectionException)11 MalformedObjectNameException (javax.management.MalformedObjectNameException)10 Test (org.junit.jupiter.api.Test)10 MBeanServerConnection (javax.management.MBeanServerConnection)9