Search in sources :

Example 36 with InstanceAlreadyExistsException

use of javax.management.InstanceAlreadyExistsException in project OpenAM by OpenRock.

the class Agent method startAgent.

/**
     *  This method starts up the monitoring agent from the
     *  common/ConfigMonitoring module (load-on-startup or at the
     *  end of AMSetupServlet/configuration).  Since web-app startup
     *  is sensitive to exceptions in load-on-startup stuff, this has
     *  quite a few try/catch blocks.
     *
     *  If any of HTML, SNMP, or RMI adaptors has a problem getting created
     *  or started, attempts to create/start the others will be made; If
     *  at least one adaptor is started, monitoring will be "active"
     *  (Agent.isRunning() will return true).
     *
     *  @param monConfig SSOServerMonConfig structure of OpenAM configuration
     *  @return 0 (zero) if at least one of HTML/SNMP/RMI adaptors started up;
     *     MON_CONFIG_DISABLED:
     *       if monitoring configured as disabled
     *     MON_MBEANSRVR_PROBLEM:
     *       if MBeanServer problem encountered
     *     MON_RMICONNECTOR_PROBLEM:
     *       if RMI connector problem
     *             (MIB not registered with MBeanServer)
     *     MON_CREATEMIB_PROBLEM:
     *       if problem creating/registering MIB
     */
public static int startAgent(SSOServerMonConfig monConfig) {
    monHtmlPort = monConfig.htmlPort;
    monSnmpPort = monConfig.snmpPort;
    monRmiPort = monConfig.rmiPort;
    monitoringEnabled = monConfig.monitoringEnabled;
    monHtmlPortEnabled = monConfig.monHtmlPortEnabled;
    monSnmpPortEnabled = monConfig.monSnmpPortEnabled;
    monRmiPortEnabled = monConfig.monRmiPortEnabled;
    monAuthFilePath = monConfig.monAuthFilePath;
    policyWindow = monConfig.policyWindow;
    sessionWindow = monConfig.sessionWindow;
    String classMethod = "Agent.startAgent:";
    // OpenAM server port comes from WebtopNaming.siteAndServerInfo
    String serverPort = agentSvrInfo.serverPort;
    // Check for Legacy MonAuthFile.
    if ((monAuthFilePath != null) && (monAuthFilePath.endsWith("opensso_mon_auth"))) {
        // Perform a rename of the old filename to the latest naming.
        File monAuthFile = new File(monAuthFilePath);
        File newMonAuthFile = new File(monAuthFile.getParentFile() + "/" + "openam_mon_auth");
        if (monAuthFile.renameTo(newMonAuthFile)) {
            monAuthFilePath = newMonAuthFile.getAbsolutePath();
        }
    }
    /*
         *  there are a lot of exception checks in this method, as
         *  it's invoked from a load-on-startup servlet.  if it
         *  chokes in here, OpenAM won't start up.
         */
    if (debug.messageEnabled()) {
        debug.message(classMethod + "entry:\n" + "    htmlPort = " + monHtmlPort + "\n" + "    authFilePath = " + monAuthFilePath + "\n" + "    snmpPort = " + monSnmpPort + "\n" + "    rmiPort = " + monRmiPort + "\n" + "    monEna = " + monitoringEnabled + "\n" + "    htmlEna = " + monHtmlPortEnabled + "\n" + "    snmpEna = " + monSnmpPortEnabled + "\n" + "    rmiEna = " + monRmiPortEnabled + "\n" + "    policyWindow = " + policyWindow + "\n" + "    sessionWindow = " + sessionWindow + "\n" + "    serverPort = " + serverPort + "\n");
    }
    if (!monitoringEnabled) {
        debug.warning(classMethod + "Monitoring configured as disabled.");
        return MON_CONFIG_DISABLED;
    }
    /*
         *  verify that the HTML, SNMP and RMI ports aren't the same as
         *  the OpenAM server port.  if HTML or SNMP conflict with it,
         *  then they'll be disabled (warning message).  if the RMI port
         *  conflicts, then all of monitoring is disabled.  there might
         *  be other ports that should be checked.
         */
    try {
        int sport = Integer.parseInt(serverPort);
        if (monRmiPort == sport) {
            debug.error(classMethod + "RMI port conflicts with OpenSSO server port (" + sport + "); Monitoring disabled.");
            return MON_RMICONNECTOR_PROBLEM;
        }
        if (monHtmlPort == sport) {
            monHtmlPortEnabled = false;
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "HTML port conflicts with OpenSSO server port (" + sport + "); Monitoring HTML port disabled.");
            }
        }
        if (monSnmpPort == sport) {
            monSnmpPortEnabled = false;
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "SNMP port conflicts with OpenSSO server port (" + sport + "); Monitoring SNMP port disabled.");
            }
        }
    } catch (NumberFormatException nfe) {
        /*
             * odd.  if serverPort's not a valid int, then there'll be
             * other problems
             */
        debug.error(classMethod + "Server port (" + serverPort + " is invalid: " + nfe.getMessage());
    }
    if (debug.messageEnabled()) {
        debug.message(classMethod + "config:\n" + "    monitoring Enabled = " + monitoringEnabled + "\n" + "    HTML Port = " + monHtmlPort + ", enabled = " + monHtmlPortEnabled + "\n" + "    SNMP Port = " + monSnmpPort + ", enabled = " + monSnmpPortEnabled + "\n" + "    RMI Port = " + monRmiPort + ", enabled = " + monRmiPortEnabled + "\n" + "    SessionWindow size = " + sessionWindow + "\n" + "    PolicyWindow size = " + policyWindow + "\n");
    }
    /*
         *  if OpenAM's deployed on a container that has MBeanServer(s),
         *  will the findMBeanServer(null) "find" those?  if so,
         *  is using the first one the right thing to do?
         */
    List<MBeanServer> servers = null;
    try {
        servers = MBeanServerFactory.findMBeanServer(null);
    } catch (SecurityException ex) {
        /*
             * if can't find one, try creating one below, although
             * if there's no findMBeanServer permission, it's unlikely
             * that there's a createMBeanServer permission...
             */
        if (debug.warningEnabled()) {
            debug.warning(classMethod + "findMBeanServer permission error: " + ex.getMessage());
        }
    }
    if (debug.messageEnabled()) {
        debug.message(classMethod + "MBeanServer list is not empty: " + ((servers != null) && !servers.isEmpty()));
    }
    if ((servers != null) && !servers.isEmpty()) {
        server = servers.get(0);
    } else {
        try {
            server = MBeanServerFactory.createMBeanServer();
        } catch (SecurityException ex) {
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "createMBeanServer permission error: " + ex.getMessage());
            }
            return MON_MBEANSRVR_PROBLEM;
        } catch (JMRuntimeException ex) {
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "createMBeanServer JMRuntime error: " + ex.getMessage());
            }
            return MON_MBEANSRVR_PROBLEM;
        } catch (ClassCastException ex) {
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "createMBeanServer ClassCast error: " + ex.getMessage());
            }
            return MON_MBEANSRVR_PROBLEM;
        }
    }
    if (server == null) {
        if (debug.warningEnabled()) {
            debug.warning(classMethod + "no MBeanServer");
        }
        return MON_MBEANSRVR_PROBLEM;
    }
    // throws no exception
    String domain = server.getDefaultDomain();
    // Create the MIB II (RFC 1213), add to the MBean server.
    try {
        sunMibObjName = new ObjectName("snmp:class=SUN_OPENSSO_SERVER_MIB");
        forgerockCtsMibObjName = new ObjectName("snmp:class=FORGEROCK_OPENAM_CTS_MIB");
        forgerockPolicyMibObjName = new ObjectName("snmp:class=FORGEROCK_OPENAM_POLICY_MIB");
        forgerockSessionMibObjName = new ObjectName("snmp:class=FORGEROCK_OPENAM_SESSION_MIB");
        if (debug.messageEnabled()) {
            debug.message(classMethod + "Adding SUN_OPENSSO_SERVER_MIB to MBean server " + "with name '" + sunMibObjName + "'");
            debug.message(classMethod + "Adding FORGEROCK_OPENAM_CTS_MIB to MBean server " + "with name '" + forgerockCtsMibObjName + "'");
        }
    } catch (MalformedObjectNameException ex) {
        // from ObjectName
        if (debug.warningEnabled()) {
            debug.warning(classMethod + "Error getting ObjectName for the MIB: " + ex.getMessage());
        }
        return MON_CREATEMIB_PROBLEM;
    }
    // Create an instance of the customized MIB
    try {
        sunMib = new SUN_OPENSSO_SERVER_MIBImpl();
        forgerockCtsMib = new FORGEROCK_OPENAM_CTS_MIBImpl();
        forgerockPolicyMib = new FORGEROCK_OPENAM_POLICY_MIBImpl();
        forgerockSessionMib = new FORGEROCK_OPENAM_SESSION_MIBImpl();
    } catch (RuntimeException ex) {
        debug.error(classMethod + "Runtime error instantiating MIB", ex);
        return MON_CREATEMIB_PROBLEM;
    } catch (Exception ex) {
        debug.error(classMethod + "Error instantiating MIB", ex);
        return MON_CREATEMIB_PROBLEM;
    }
    try {
        server.registerMBean(sunMib, sunMibObjName);
        server.registerMBean(forgerockCtsMib, forgerockCtsMibObjName);
        server.registerMBean(forgerockPolicyMib, forgerockPolicyMibObjName);
        server.registerMBean(forgerockSessionMib, forgerockSessionMibObjName);
    } catch (RuntimeOperationsException ex) {
        // from registerMBean
        if (debug.warningEnabled()) {
            debug.warning(classMethod + "Null parameter or no object name for MIB specified: " + ex.getMessage());
        }
        return MON_CREATEMIB_PROBLEM;
    } catch (InstanceAlreadyExistsException ex) {
        // from registerMBean
        if (debug.warningEnabled()) {
            debug.warning(classMethod + "Error registering MIB MBean: " + ex.getMessage());
        }
    // probably can just continue
    } catch (MBeanRegistrationException ex) {
        // from registerMBean
        if (debug.warningEnabled()) {
            debug.warning(classMethod + "Error registering MIB MBean: " + ex.getMessage());
        }
        return MON_CREATEMIB_PROBLEM;
    } catch (NotCompliantMBeanException ex) {
        // from registerMBean
        if (debug.warningEnabled()) {
            debug.warning(classMethod + "Error registering MIB MBean: " + ex.getMessage());
        }
        return MON_CREATEMIB_PROBLEM;
    }
    /*
         *  now that we have the MBeanServer, see if the HTML,
         *  SNMP and RMI adaptors specified will start up
         */
    boolean monHTMLStarted = false;
    boolean monSNMPStarted = false;
    boolean monRMIStarted = false;
    // HTML port adaptor
    if (monHtmlPortEnabled) {
        // Create and start the HTML adaptor.
        try {
            htmlObjName = new ObjectName(domain + ":class=HtmlAdaptorServer,protocol=html,port=" + monHtmlPort);
            if (debug.messageEnabled()) {
                debug.message(classMethod + "Adding HTML adaptor to MBean server with name '" + htmlObjName + "'\n    " + "HTML adaptor is bound on TCP port " + monHtmlPort);
            }
            Map<String, String> users = MonitoringUtil.getMonAuthList(monAuthFilePath);
            if (users != null) {
                AuthInfo[] authInfo = new AuthInfo[users.size()];
                int i = 0;
                for (Map.Entry<String, String> entry : users.entrySet()) {
                    authInfo[i] = new AuthInfo(entry.getKey(), entry.getValue());
                    i++;
                }
                htmlAdaptor = new HtmlAdaptorServer(monHtmlPort, authInfo);
            } else {
                if (debug.warningEnabled()) {
                    debug.warning(classMethod + "HTML monitoring interface disabled; no " + "authentication file found");
                }
                htmlAdaptor = null;
            }
            if (htmlAdaptor == null) {
                if (debug.warningEnabled()) {
                    debug.warning(classMethod + "HTTP port " + monHtmlPort + " unavailable or invalid. " + "Monitoring HTML adaptor not started.");
                }
            } else {
                server.registerMBean(htmlAdaptor, htmlObjName);
                // throws no exception
                htmlAdaptor.start();
                monHTMLStarted = true;
            }
        } catch (MalformedObjectNameException ex) {
            // from ObjectName
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error getting ObjectName for HTML adaptor: " + ex.getMessage());
            }
        } catch (NullPointerException ex) {
            // from ObjectName
            debug.error(classMethod + "NPE getting ObjectName for HTML adaptor", ex);
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "NPE getting ObjectName for HTML adaptor: " + ex.getMessage());
            }
        } catch (InstanceAlreadyExistsException ex) {
            // from registerMBean
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error registering HTML adaptor MBean: " + ex.getMessage());
            }
        } catch (MBeanRegistrationException ex) {
            // from registerMBean
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error registering HTML adaptor MBean: " + ex.getMessage());
            }
        } catch (NotCompliantMBeanException ex) {
            // from registerMBean
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error registering HTML adaptor MBean: " + ex.getMessage());
            }
        }
    } else {
        debug.warning(classMethod + "Monitoring HTML port not enabled in configuration.");
    }
    // SNMP port adaptor
    if (monSnmpPortEnabled) {
        /*
             * Create and start the SNMP adaptor.
             * Specify the port to use in the constructor. 
             * The standard port for SNMP is 161.
             */
        try {
            snmpObjName = new ObjectName(domain + ":class=SnmpAdaptorServer,protocol=snmp,port=" + monSnmpPort);
            if (debug.messageEnabled()) {
                debug.message(classMethod + "Adding SNMP adaptor to MBean server with name '" + snmpObjName + "'\n    " + "SNMP Adaptor is bound on UDP port " + monSnmpPort);
            }
            // no exc
            snmpAdaptor = new SnmpAdaptorServer(monSnmpPort);
            if (snmpAdaptor == null) {
                if (debug.warningEnabled()) {
                    debug.warning(classMethod + "Unable to get SNMP adaptor.");
                }
            } else {
                server.registerMBean(snmpAdaptor, snmpObjName);
                // throws no exception
                snmpAdaptor.start();
                /*
                     *  Send a coldStart SNMP Trap.
                     *  Use port = monSnmpPort+1.
                     */
                if (debug.messageEnabled()) {
                    debug.message(classMethod + "Sending a coldStart SNMP trap to each " + "destination defined in the ACL file...");
                }
                snmpAdaptor.setTrapPort(new Integer(monSnmpPort + 1));
                snmpAdaptor.snmpV1Trap(0, 0, null);
                if (debug.messageEnabled()) {
                    debug.message(classMethod + "Done sending coldStart.");
                }
                /*
                     *  Bind the SNMP adaptor to the MIB in order to make the
                     *  MIB accessible through the SNMP protocol adaptor.
                     *  If this step is not performed, the MIB will still live
                     *  in the Java DMK agent:
                     *  its objects will be addressable through HTML but not
                     *  SNMP.
                     */
                // throws no exception
                sunMib.setSnmpAdaptor(snmpAdaptor);
                forgerockCtsMib.setSnmpAdaptor(snmpAdaptor);
                forgerockPolicyMib.setSnmpAdaptor(snmpAdaptor);
                forgerockSessionMib.setSnmpAdaptor(snmpAdaptor);
                monSNMPStarted = true;
            }
        } catch (Exception ex) {
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error while setting up SNMP adaptor " + ex.getMessage());
            }
            if (ex instanceof IOException || ex instanceof SnmpStatusException) {
                // should be from the snmpV1Trap call, which
                //*shouldn't* affect the rest of snmp operations...
                monSNMPStarted = true;
            }
        }
    } else {
        debug.warning(classMethod + "Monitoring SNMP port not enabled.");
    }
    // RMI port adaptor
    if (monRmiPortEnabled) {
        // Create an RMI connector and start it
        try {
            registry = LocateRegistry.createRegistry(monRmiPort);
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + monRmiPort + "/server");
            cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
            cs.start();
            monRMIStarted = true;
        //                /*
        //                 *  Create a LinkTrapGenerator.
        //                 *  Specify the ifIndex to use in the object name.
        //                 */
        //                String trapGeneratorClass = "LinkTrapGenerator";
        //                int ifIndex = 1;
        //                trapGeneratorObjName = new ObjectName("trapGenerator" + 
        //                    ":class=LinkTrapGenerator,ifIndex=" + ifIndex);
        //                if (debug.messageEnabled()) {
        //                    debug.message(classMethod +
        //                        "Adding LinkTrapGenerator to MBean server " +
        //                        "with name '" +
        //                        trapGeneratorObjName + "'");
        //                }
        //
        //                LinkTrapGenerator trapGenerator =
        //                    new LinkTrapGenerator(nbTraps);
        //                server.registerMBean(trapGenerator, trapGeneratorObjName);
        //
        } catch (MalformedURLException ex) {
            /*
                 * from JMXServiceURL or
                 * JMXConnectorServerFactory.JMXConnectorServer
                 */
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error getting JMXServiceURL or JMXConnectorServer " + "for RMI adaptor: " + ex.getMessage());
            }
        } catch (NullPointerException ex) {
            /*
                 * from JMXServiceURL or
                 * JMXConnectorServerFactory.JMXConnectorServer
                 */
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error getting JMXServiceURL or JMXConnectorServer " + "for RMI adaptor: " + ex.getMessage());
            }
        } catch (IOException ex) {
            /*
                 * from JMXConnectorServerFactory.JMXConnectorServer or
                 * JMXConnectorServer.start
                 */
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Error getting JMXConnectorServer for, or starting " + "RMI adaptor: " + ex.getMessage());
            }
        } catch (IllegalStateException ex) {
            // from JMXConnectorServer.start
            if (debug.warningEnabled()) {
                debug.warning(classMethod + "Illegal State Error from JMXConnectorServer for " + "RMI adaptor: " + ex.getMessage());
            }
        } catch (Exception ex) {
            /*
                 * compiler says that JMXProviderException and
                 * NullPointerException already caught
                 */
            debug.error(classMethod + "Error starting RMI: executing rmiregistry " + monRmiPort + ".", ex);
        }
    } else {
        debug.warning(classMethod + "Monitoring RMI port not enabled.");
    }
    /*
         * the HTML and SNMP adaptors may or may not be started,
         * but if the RMI connector had a problem, monitoring is
         * non-functional, as the opensso MIB didn't get registered.
         */
    if (!monRMIStarted && !monSNMPStarted && !monHTMLStarted) {
        debug.warning(classMethod + "No Monitoring interfaces started; monitoring disabled.");
        return MON_RMICONNECTOR_PROBLEM;
    } else {
        // if all/enough has gone well
        agentStarted = true;
        startMonitoringAgent(agentSvrInfo);
        return 0;
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) JMRuntimeException(javax.management.JMRuntimeException) SnmpAdaptorServer(com.sun.management.comm.SnmpAdaptorServer) FORGEROCK_OPENAM_SESSION_MIBImpl(org.forgerock.openam.monitoring.session.FORGEROCK_OPENAM_SESSION_MIBImpl) JMRuntimeException(javax.management.JMRuntimeException) MBeanServer(javax.management.MBeanServer) RuntimeOperationsException(javax.management.RuntimeOperationsException) JMXServiceURL(javax.management.remote.JMXServiceURL) SnmpStatusException(com.sun.management.snmp.SnmpStatusException) MalformedObjectNameException(javax.management.MalformedObjectNameException) AuthInfo(com.sun.jdmk.comm.AuthInfo) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) IOException(java.io.IOException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) MalformedObjectNameException(javax.management.MalformedObjectNameException) JMException(javax.management.JMException) RuntimeOperationsException(javax.management.RuntimeOperationsException) SnmpStatusException(com.sun.management.snmp.SnmpStatusException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) JMRuntimeException(javax.management.JMRuntimeException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ObjectName(javax.management.ObjectName) FORGEROCK_OPENAM_CTS_MIBImpl(org.forgerock.openam.monitoring.cts.FORGEROCK_OPENAM_CTS_MIBImpl) FORGEROCK_OPENAM_POLICY_MIBImpl(org.forgerock.openam.monitoring.policy.FORGEROCK_OPENAM_POLICY_MIBImpl) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) HtmlAdaptorServer(com.sun.jdmk.comm.HtmlAdaptorServer) MBeanRegistrationException(javax.management.MBeanRegistrationException)

Example 37 with InstanceAlreadyExistsException

use of javax.management.InstanceAlreadyExistsException in project quasar by puniverse.

the class JMXForkJoinPoolMonitor method registerMBean.

protected void registerMBean() {
    try {
        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        final ObjectName mxbeanName = new ObjectName(mbeanName);
        mbs.registerMBean(this, mxbeanName);
        this.registered = true;
    } catch (InstanceAlreadyExistsException ex) {
        throw new RuntimeException(ex);
    } catch (MBeanRegistrationException ex) {
        ex.printStackTrace();
    } catch (NotCompliantMBeanException ex) {
        throw new AssertionError(ex);
    } catch (MalformedObjectNameException ex) {
        throw new AssertionError(ex);
    }
}
Also used : MalformedObjectNameException(javax.management.MalformedObjectNameException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) MBeanRegistrationException(javax.management.MBeanRegistrationException) MBeanServer(javax.management.MBeanServer) ObjectName(javax.management.ObjectName)

Example 38 with InstanceAlreadyExistsException

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

the class DefaultMBeanServerInterceptor method registerDynamicMBean.

private ObjectInstance registerDynamicMBean(String classname, DynamicMBean mbean, ObjectName name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
    name = nonDefaultDomain(name);
    if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
        MBEANSERVER_LOGGER.logp(Level.FINER, DefaultMBeanServerInterceptor.class.getName(), "registerMBean", "ObjectName = " + name);
    }
    ObjectName logicalName = preRegister(mbean, server, name);
    // preRegister returned successfully, so from this point on we
    // must call postRegister(false) if there is any problem.
    boolean registered = false;
    boolean registerFailed = false;
    ResourceContext context = null;
    try {
        if (mbean instanceof DynamicMBean2) {
            try {
                ((DynamicMBean2) mbean).preRegister2(server, logicalName);
                // until we succeed
                registerFailed = true;
            } catch (Exception e) {
                if (e instanceof RuntimeException)
                    throw (RuntimeException) e;
                if (e instanceof InstanceAlreadyExistsException)
                    throw (InstanceAlreadyExistsException) e;
                throw new RuntimeException(e);
            }
        }
        if (logicalName != name && logicalName != null) {
            logicalName = ObjectName.getInstance(nonDefaultDomain(logicalName));
        }
        checkMBeanPermission(classname, null, logicalName, "registerMBean");
        if (logicalName == null) {
            final RuntimeException wrapped = new IllegalArgumentException("No object name specified");
            throw new RuntimeOperationsException(wrapped, "Exception occurred trying to register the MBean");
        }
        final Object resource = getResource(mbean);
        // Register the MBean with the repository.
        // Returns the resource context that was used.
        // The returned context does nothing for regular MBeans.
        // For ClassLoader MBeans the context makes it possible to register these
        // objects with the appropriate framework artifacts, such as
        // the CLR, from within the repository lock.
        // In case of success, we also need to call context.done() at the
        // end of this method.
        //
        context = registerWithRepository(resource, mbean, logicalName);
        registerFailed = false;
        registered = true;
    } finally {
        try {
            postRegister(logicalName, mbean, registered, registerFailed);
        } finally {
            if (registered && context != null)
                context.done();
        }
    }
    return new ObjectInstance(logicalName, classname);
}
Also used : JMRuntimeException(javax.management.JMRuntimeException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) ObjectInstance(javax.management.ObjectInstance) NamedObject(com.sun.jmx.mbeanserver.NamedObject) IntrospectionException(javax.management.IntrospectionException) OperationsException(javax.management.OperationsException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) ReflectionException(javax.management.ReflectionException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) RuntimeMBeanException(javax.management.RuntimeMBeanException) RuntimeErrorException(javax.management.RuntimeErrorException) ListenerNotFoundException(javax.management.ListenerNotFoundException) RuntimeOperationsException(javax.management.RuntimeOperationsException) AttributeNotFoundException(javax.management.AttributeNotFoundException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) JMRuntimeException(javax.management.JMRuntimeException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) MBeanException(javax.management.MBeanException) ObjectName(javax.management.ObjectName) DynamicMBean2(com.sun.jmx.mbeanserver.DynamicMBean2) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 39 with InstanceAlreadyExistsException

use of javax.management.InstanceAlreadyExistsException 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 40 with InstanceAlreadyExistsException

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

the class MXBeanRefTest method main.

public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    ObjectName productName = new ObjectName("d:type=Product,n=1");
    ObjectName product2Name = new ObjectName("d:type=Product,n=2");
    ObjectName moduleName = new ObjectName("d:type=Module");
    mbs.registerMBean(product, productName);
    mbs.registerMBean(product2, product2Name);
    mbs.registerMBean(module, moduleName);
    ModuleMXBean moduleProxy = JMX.newMXBeanProxy(mbs, moduleName, ModuleMXBean.class);
    ObjectName on;
    on = (ObjectName) mbs.getAttribute(moduleName, "Product");
    check("ObjectName attribute value", on.equals(productName));
    ProductMXBean productProxy = moduleProxy.getProduct();
    MBeanServerInvocationHandler mbsih = (MBeanServerInvocationHandler) Proxy.getInvocationHandler(productProxy);
    check("ObjectName in proxy", mbsih.getObjectName().equals(productName));
    mbs.setAttribute(moduleName, new Attribute("Product", product2Name));
    ProductMXBean product2Proxy = module.getProduct();
    mbsih = (MBeanServerInvocationHandler) Proxy.getInvocationHandler(product2Proxy);
    check("Proxy after setAttribute", mbsih.getObjectName().equals(product2Name));
    moduleProxy.setProduct(productProxy);
    ProductMXBean productProxyAgain = module.getProduct();
    mbsih = (MBeanServerInvocationHandler) Proxy.getInvocationHandler(productProxyAgain);
    check("Proxy after proxied set", mbsih.getObjectName().equals(productName));
    MBeanServer mbs2 = MBeanServerFactory.createMBeanServer();
    ProductMXBean productProxy2 = JMX.newMXBeanProxy(mbs2, productName, ProductMXBean.class);
    try {
        moduleProxy.setProduct(productProxy2);
        check("Proxy for wrong MBeanServer worked but shouldn't", false);
    } catch (Exception e) {
        if (e instanceof UndeclaredThrowableException && e.getCause() instanceof OpenDataException)
            check("Proxy for wrong MBeanServer correctly rejected", true);
        else {
            e.printStackTrace(System.out);
            check("Proxy for wrong MBeanServer got wrong exception", false);
        }
    }
    // Test 6283873
    ObjectName dup = new ObjectName("a:b=c");
    mbs.registerMBean(new MBeanServerDelegate(), dup);
    try {
        mbs.registerMBean(new ProductImpl(), dup);
        check("Duplicate register succeeded but should fail", false);
    } catch (InstanceAlreadyExistsException e) {
        check("Got correct exception from duplicate name", true);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        check("Got wrong exception from duplicate name", false);
    }
    if (failure != null)
        throw new Exception("TEST FAILED: " + failure);
    System.out.println("TEST PASSED");
}
Also used : Attribute(javax.management.Attribute) OpenDataException(javax.management.openmbean.OpenDataException) MBeanServerDelegate(javax.management.MBeanServerDelegate) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) MBeanServerInvocationHandler(javax.management.MBeanServerInvocationHandler) OpenDataException(javax.management.openmbean.OpenDataException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) MBeanServer(javax.management.MBeanServer) ObjectName(javax.management.ObjectName)

Aggregations

InstanceAlreadyExistsException (javax.management.InstanceAlreadyExistsException)49 ObjectName (javax.management.ObjectName)38 MalformedObjectNameException (javax.management.MalformedObjectNameException)30 MBeanRegistrationException (javax.management.MBeanRegistrationException)29 NotCompliantMBeanException (javax.management.NotCompliantMBeanException)28 MBeanServer (javax.management.MBeanServer)25 InstanceNotFoundException (javax.management.InstanceNotFoundException)14 ObjectInstance (javax.management.ObjectInstance)8 IOException (java.io.IOException)6 StandardMBean (javax.management.StandardMBean)6 Test (org.junit.Test)3 MalformedURLException (java.net.MalformedURLException)2 CacheException (javax.cache.CacheException)2 JMRuntimeException (javax.management.JMRuntimeException)2 MBeanException (javax.management.MBeanException)2 ReflectionException (javax.management.ReflectionException)2 RuntimeOperationsException (javax.management.RuntimeOperationsException)2 Logger (ch.qos.logback.classic.Logger)1 JMXConfigurator (ch.qos.logback.classic.jmx.JMXConfigurator)1 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)1