Example usage for javax.management MBeanServer setAttribute

List of usage examples for javax.management MBeanServer setAttribute

Introduction

In this page you can find the example usage for javax.management MBeanServer setAttribute.

Prototype

public void setAttribute(ObjectName name, Attribute attribute) throws InstanceNotFoundException,
        AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException;

Source Link

Usage

From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java

protected void setAttributeJmx(String name, String attribute, Object arguments) throws Exception {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName oname = server.queryNames(new ObjectName(name), null).iterator().next();
    server.setAttribute(oname, new Attribute(attribute, arguments));
}

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

private MBeanServer initMBeanServer(MBeanServerConfig conf) throws Exception {
    mx4j.log.Log.redirectTo(new CommonsLogger());
    //  make sure that MX4j Server builder is used
    String oldSysProp = System.getProperty("javax.management.builder.initial");
    System.setProperty("javax.management.builder.initial", "mx4j.server.MX4JMBeanServerBuilder");
    MBeanServer server = MBeanServerFactory.createMBeanServer("UPNPLib");
    if (oldSysProp != null) {
        System.setProperty("javax.management.builder.initial", oldSysProp);
    }//w  w  w .jav  a2 s  . c  o  m
    ObjectName serverName = new ObjectName("Http:name=HttpAdaptor");
    server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", serverName, null);
    // set attributes
    server.setAttribute(serverName, new Attribute("Port", new Integer(conf.adapterAdapterPort)));

    Boolean allowWanBool = new Boolean(conf.allowWan);
    if (allowWanBool.booleanValue()) {
        server.setAttribute(serverName, new Attribute("Host", "0.0.0.0"));
    } else {
        server.setAttribute(serverName, new Attribute("Host", "localhost"));
    }

    ObjectName processorName = new ObjectName("Http:name=XSLTProcessor");
    server.createMBean("mx4j.tools.adaptor.http.XSLTProcessor", processorName, null);
    server.setAttribute(processorName, new Attribute("LocaleString", conf.locale));

    server.setAttribute(processorName, new Attribute("UseCache", Boolean.FALSE));

    server.setAttribute(processorName, new Attribute("PathInJar", "net/sbbi/jmx/xsl"));

    server.setAttribute(serverName, new Attribute("ProcessorName", processorName));
    // add user names
    server.invoke(serverName, "addAuthorization", new Object[] { conf.adapterUserName, conf.adapterPassword },
            new String[] { "java.lang.String", "java.lang.String" });
    // use basic authentication
    server.setAttribute(serverName, new Attribute("AuthenticationMethod", "basic"));
    // starts the server
    server.invoke(serverName, "start", null, null);

    return server;
}

From source file:org.apache.servicemix.jbi.deployer.impl.ComponentInstaller.java

public void configure(Properties props) throws Exception {
    if (props != null && props.size() > 0) {
        ObjectName on = getInstallerConfigurationMBean();
        if (on == null) {
            LOGGER.warn(//from   w  w w.  j  ava2s  .  c o m
                    "Could not find installation configuration MBean. Installation properties will be ignored.");
        } else {
            MBeanServer mbs = deployer.getMbeanServer();
            for (Object o : props.keySet()) {
                String key = (String) o;
                String val = props.getProperty(key);
                try {
                    mbs.setAttribute(on, new Attribute(key, val));
                } catch (JMException e) {
                    throw new DeploymentException("Could not set installation property: (" + key + " = " + val,
                            e);
                }
            }
        }
    }
}

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

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file/* w  w w .j  a v  a  2 s .c o  m*/
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSar(File file, String warDirectoryPath) throws IOException {
    ZipFile zip = new ZipFile(file);
    ZipEntry ze = null;
    String fileName = file.getName();
    fileName = fileName.substring(0, fileName.indexOf('.'));
    fileName += "sar";
    String fileDirectory;
    CopyOnWriteArrayList classPath = new CopyOnWriteArrayList();
    Enumeration<? extends ZipEntry> entries = zip.entries();
    int numBytes;
    while (entries.hasMoreElements()) {
        ze = entries.nextElement();
        // //System.out.println("Unzipping " + ze.getName());
        String filePath = deployDirectory + "/" + fileName + "/" + ze.getName();
        if (!ze.isDirectory()) {
            fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
        } else {
            fileDirectory = filePath;
        }
        // //System.out.println(fileDirectory);
        createDirectory(fileDirectory);
        if (!ze.isDirectory()) {
            FileOutputStream fout = new FileOutputStream(filePath);
            byte[] inputbyt = new byte[8192];
            InputStream istream = zip.getInputStream(ze);
            while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                fout.write(inputbyt, 0, numBytes);
            }
            fout.close();
            istream.close();
            if (ze.getName().endsWith(".jar")) {
                classPath.add(filePath);
            }
        }
    }
    zip.close();
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader = new WebClassLoader(urls);
    for (int index = 0; index < classPath.size(); index++) {
        System.out.println("file:" + classPath.get(index));
        new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader);
    }
    new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader);
    sarsMap.put(fileName, sarClassLoader);
    System.out.println(sarClassLoader.geturlS());
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            System.out.println(mbean.getObjectname());
            System.out.println(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class helloWorldService = sarClassLoader.loadClass(mbean.getCls());
            Object obj = helloWorldService.newInstance();
            if (mbs.isRegistered(objName)) {
                mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbs.unregisterMBean(objName);
            }
            mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbs.setAttribute(objName, mbeanattribute);
                }
            }
            mbs.invoke(objName, "startService", null, null);
        }
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedObjectNameException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceAlreadyExistsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanRegistrationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotCompliantMBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ReflectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAttributeValueException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AttributeNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.openejb.server.cli.command.LocalJMXCommand.java

private void set(final String cmd) {
    final String[] split = cmd.split(" ");
    if (split.length < 2) {
        streamManager.writeErr("you need to specify an attribute, an objectname and a value");
        return;//from  w w w.ja  va 2 s.c o  m
    }

    final MBeanServer mBeanServer = LocalMBeanServer.get();
    final String newValue = cmd.substring(split[0].length() + split[1].length() + 1).trim();
    try {
        final ObjectName oname = new ObjectName(split[1]);
        final MBeanInfo minfo = mBeanServer.getMBeanInfo(oname);
        final MBeanAttributeInfo attrs[] = minfo.getAttributes();

        String type = String.class.getName();
        for (int i = 0; i < attrs.length; i++) {
            if (attrs[i].getName().equals(split[0])) {
                type = attrs[i].getType();
                break;
            }
        }

        final Object valueObj = PropertyEditors.getValue(type, newValue,
                Thread.currentThread().getContextClassLoader());
        mBeanServer.setAttribute(oname, new Attribute(split[0], valueObj));
        streamManager.writeOut("done");
    } catch (Exception ex) {
        streamManager.writeOut("Error - " + ex.toString());
    }
}

From source file:org.jumpmind.symmetric.SymmetricWebServer.java

protected void registerHttpJmxAdaptor(int jmxPort) throws Exception {
    if (AppUtils.isSystemPropertySet(SystemConstants.SYSPROP_JMX_HTTP_CONSOLE_ENABLED, true) && jmxEnabled) {
        log.info("Starting JMX HTTP console on port {}", jmxPort);
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = getHttpJmxAdaptorName();
        mbeanServer.createMBean(HttpAdaptor.class.getName(), name);
        if (!AppUtils.isSystemPropertySet(SystemConstants.SYSPROP_JMX_HTTP_CONSOLE_LOCALHOST_ENABLED, true)) {
            mbeanServer.setAttribute(name, new Attribute("Host", "0.0.0.0"));
        } else if (StringUtils.isNotBlank(host)) {
            mbeanServer.setAttribute(name, new Attribute("Host", host));
        }/*ww  w  .ja  va2 s . c  o m*/
        mbeanServer.setAttribute(name, new Attribute("Port", new Integer(jmxPort)));
        ObjectName processorName = getXslJmxAdaptorName();
        mbeanServer.createMBean(XSLTProcessor.class.getName(), processorName);
        mbeanServer.setAttribute(name, new Attribute("ProcessorName", processorName));
        mbeanServer.invoke(name, "start", null, null);
    }
}

From source file:org.mc4j.ems.impl.jmx.connection.bean.attribute.DAttribute.java

/**
 * Set the attribute on the server//  w  w  w  .j a  va  2  s .co m
 *
 * @param newValue The value to be set
 * @throws Exception
 */
public void setValue(Object newValue) throws Exception {

    try {
        MBeanServer server = bean.getConnectionProvider().getMBeanServer();
        server.setAttribute(bean.getObjectName(), new Attribute(getName(), newValue));
        alterValue(newValue);
    } catch (Exception e) {
        throw new InvocationTargetException(e);
    }
    refresh();
}

From source file:org.rhq.enterprise.gui.startup.StartupServlet.java

/**
 * Starts the embedded agent, but only if the embedded agent is installed and it is enabled.
 *
 * @throws ServletException if the agent is installed and enabled but failed to start
 *//*from ww w  . ja v a2  s. co  m*/
private void startEmbeddedAgent() throws ServletException {
    // we can't use EmbeddedAgentBootstrapServiceMBean because if the embedded agent
    // isn't installed, that class will not be available; we must use JMX API
    final ObjectName agentBootstrapMBean = ObjectNameFactory.create("rhq:service=EmbeddedAgentBootstrap");
    final String agentEnabledAttribute = "AgentEnabled";
    final String startAgentMethod = "startAgent";
    final String configurationOverridesAttribute = "ConfigurationOverrides";
    final MBeanServer mbs = MBeanServerLocator.locateJBoss();

    try {
        // this will fail if the embedded agent isn't installed
        String enabled = (String) mbs.getAttribute(agentBootstrapMBean, agentEnabledAttribute);

        // if we got this far, the embedded agent is at least installed
        // now check to see if its enabled - if so start it; any startup exceptions now are thrown
        try {
            if (Boolean.valueOf(enabled)) {
                log.info("The embedded Agent is installed and enabled - it will now be started...");

                // NOTE: we cannot directly import AgentConfigurationConstants, so we hardcode the
                // actual constant values here - need to keep an eye on these in the unlikely event
                // the constant values change.
                String AgentConfigurationConstants_SERVER_TRANSPORT = "rhq.agent.server.transport";
                String AgentConfigurationConstants_SERVER_BIND_ADDRESS = "rhq.agent.server.bind-address";
                String AgentConfigurationConstants_SERVER_BIND_PORT = "rhq.agent.server.bind-port";

                // Get the configuration overrides as set in the configuration file.
                // If the agent's bind address isn't overridden with a non-empty value,
                // then we need to get the Server bind address and use it for the agent's bind address.
                // If the agent's server endpoint address/port are empty, we again use the values
                // appropriate for the Server this agent is embedded in.
                // Note that we don't look for the values in persisted preferences - we assume they
                // are always present in the configuration overrides (which they should always be);
                Properties overrides;
                String serverTransport;
                String serverAddress;
                String serverPort;
                String agentAddress;

                overrides = (Properties) mbs.getAttribute(agentBootstrapMBean, configurationOverridesAttribute);

                serverTransport = overrides.getProperty(AgentConfigurationConstants_SERVER_TRANSPORT);
                serverAddress = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS);
                serverPort = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_PORT);
                agentAddress = overrides
                        .getProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS);

                Server server = LookupUtil.getServerManager().getServer();

                if (agentAddress == null || agentAddress.trim().equals("")) {
                    overrides.setProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS,
                            server.getAddress());
                }
                if (serverAddress == null || serverAddress.trim().equals("")) {
                    overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS, server.getAddress());
                }
                if (serverPort == null || serverPort.trim().equals("")) {
                    if (SecurityUtil.isTransportSecure(serverTransport)) {
                        overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT,
                                Integer.toString(server.getSecurePort()));
                    } else {
                        overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT,
                                Integer.toString(server.getPort()));
                    }
                }

                mbs.setAttribute(agentBootstrapMBean,
                        new Attribute(configurationOverridesAttribute, overrides));

                // We need to do the agent startup in a separate thread so we do not hang
                // this startup servlet.  JBossAS 4.2 will not begin accepting HTTP requests
                // until this startup servlet has finished (this is different from JBossAS 4.0).
                // The agent needs to submit an HTTP request in order to complete its startup
                // (it needs to register with the server).
                // The side effect of this is the RHQ Server will still start even if the embedded
                // agent fails to start - this may not be a bad thing.  We probably do not want
                // the entire RHQ Server to go down if its agent fails to start.
                Runnable agentStartRunnable = new Runnable() {
                    public void run() {
                        // this returns only when the agent has started and is registered (sends HTTP request)
                        try {
                            mbs.invoke(agentBootstrapMBean, startAgentMethod, new Object[0], new String[0]);
                        } catch (Throwable t) {
                            log.error("Failed to start the embedded Agent - it will not be available!", t);
                        }
                    }
                };

                Thread agentStartThread = new Thread(agentStartRunnable, "Embedded Agent Startup");
                agentStartThread.setDaemon(true);
                agentStartThread.start();
            } else {
                log.debug("The embedded Agent is not enabled, so it will not be started.");
            }
        } catch (Throwable t) {
            throw new ServletException("Failed to start the embedded Agent.", t);
        }
    } catch (ServletException se) {
        throw se;
    } catch (Throwable t) {
        log.info("The embedded Agent is not installed, so it will not be started (" + t + ").");
    }

    return;
}

From source file:org.rhq.enterprise.server.core.StartupBean.java

/**
 * Starts the embedded agent, but only if the embedded agent is installed and it is enabled.
 *
 * @throws RuntimeException if the agent is installed and enabled but failed to start
 *
 * @deprecated we don't have an embedded agent anymore, leaving this in case we resurrect it
 *//* w w w. j  av a  2  s .  com*/
@Deprecated
private void startEmbeddedAgent() throws RuntimeException {
    // we can't use EmbeddedAgentBootstrapServiceMBean because if the embedded agent
    // isn't installed, that class will not be available; we must use JMX API
    final ObjectName agentBootstrapMBean = ObjectNameFactory.create("rhq:service=EmbeddedAgentBootstrap");
    final String agentEnabledAttribute = "AgentEnabled";
    final String startAgentMethod = "startAgent";
    final String configurationOverridesAttribute = "ConfigurationOverrides";
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    try {
        // this will fail if the embedded agent isn't installed
        String enabled = (String) mbs.getAttribute(agentBootstrapMBean, agentEnabledAttribute);

        // if we got this far, the embedded agent is at least installed
        // now check to see if its enabled - if so start it; any startup exceptions now are thrown
        try {
            if (Boolean.valueOf(enabled)) {
                log.info("The embedded Agent is installed and enabled - it will now be started...");

                // NOTE: we cannot directly import AgentConfigurationConstants, so we hardcode the
                // actual constant values here - need to keep an eye on these in the unlikely event
                // the constant values change.
                String AgentConfigurationConstants_SERVER_TRANSPORT = "rhq.agent.server.transport";
                String AgentConfigurationConstants_SERVER_BIND_ADDRESS = "rhq.agent.server.bind-address";
                String AgentConfigurationConstants_SERVER_BIND_PORT = "rhq.agent.server.bind-port";

                // Get the configuration overrides as set in the configuration file.
                // If the agent's bind address isn't overridden with a non-empty value,
                // then we need to get the Server bind address and use it for the agent's bind address.
                // If the agent's server endpoint address/port are empty, we again use the values
                // appropriate for the Server this agent is embedded in.
                // Note that we don't look for the values in persisted preferences - we assume they
                // are always present in the configuration overrides (which they should always be);
                Properties overrides;
                String serverTransport;
                String serverAddress;
                String serverPort;
                String agentAddress;

                overrides = (Properties) mbs.getAttribute(agentBootstrapMBean, configurationOverridesAttribute);

                serverTransport = overrides.getProperty(AgentConfigurationConstants_SERVER_TRANSPORT);
                serverAddress = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS);
                serverPort = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_PORT);
                agentAddress = overrides
                        .getProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS);

                Server server = serverManager.getServer();

                if (agentAddress == null || agentAddress.trim().equals("")) {
                    overrides.setProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS,
                            server.getAddress());
                }
                if (serverAddress == null || serverAddress.trim().equals("")) {
                    overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS, server.getAddress());
                }
                if (serverPort == null || serverPort.trim().equals("")) {
                    if (SecurityUtil.isTransportSecure(serverTransport)) {
                        overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT,
                                Integer.toString(server.getSecurePort()));
                    } else {
                        overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT,
                                Integer.toString(server.getPort()));
                    }
                }

                mbs.setAttribute(agentBootstrapMBean,
                        new Attribute(configurationOverridesAttribute, overrides));

                // We need to do the agent startup in a separate thread so we do not hang
                // this startup servlet.  JBossAS 4.2 will not begin accepting HTTP requests
                // until this startup servlet has finished (this is different from JBossAS 4.0).
                // The agent needs to submit an HTTP request in order to complete its startup
                // (it needs to register with the server).
                // The side effect of this is the RHQ Server will still start even if the embedded
                // agent fails to start - this may not be a bad thing.  We probably do not want
                // the entire RHQ Server to go down if its agent fails to start.
                Runnable agentStartRunnable = new Runnable() {
                    public void run() {
                        // this returns only when the agent has started and is registered (sends HTTP request)
                        try {
                            mbs.invoke(agentBootstrapMBean, startAgentMethod, new Object[0], new String[0]);
                        } catch (Throwable t) {
                            log.error("Failed to start the embedded Agent - it will not be available!", t);
                        }
                    }
                };

                Thread agentStartThread = new Thread(agentStartRunnable, "Embedded Agent Startup");
                agentStartThread.setDaemon(true);
                agentStartThread.start();
            } else {
                log.debug("The embedded Agent is not enabled, so it will not be started.");
            }
        } catch (Throwable t) {
            throw new RuntimeException("Failed to start the embedded Agent.", t);
        }
    } catch (RuntimeException se) {
        throw se;
    } catch (Throwable t) {
        log.info("The embedded Agent is not installed, so it will not be started (" + t + ").");
    }

    return;
}