001/*
002 * Copyright 2013 Atteo.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.atteo.moonshine.jmx;
017
018import java.io.IOException;
019import java.lang.management.ManagementFactory;
020import java.net.MalformedURLException;
021import java.util.HashMap;
022
023import javax.inject.Inject;
024import javax.management.MBeanServer;
025import javax.management.remote.JMXConnectorServer;
026import javax.management.remote.JMXConnectorServerFactory;
027import javax.management.remote.JMXServiceURL;
028import javax.xml.bind.annotation.XmlElement;
029import javax.xml.bind.annotation.XmlIDREF;
030import javax.xml.bind.annotation.XmlRootElement;
031
032import org.atteo.moonshine.services.ImportService;
033import org.atteo.moonshine.TopLevelService;
034
035/**
036 * Publishes JMX MBeanServer through RMI.
037 *
038 * @see <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html">Monitoring and Management Using JMX Technology</a>
039 */
040@XmlRootElement(name = "publishJmx")
041public class PublishJmx extends TopLevelService {
042    /**
043     * JMX MBeanServer to publish.
044     */
045    @XmlElement
046    @XmlIDREF
047    @ImportService
048    private JMX jmx;
049
050    /**
051     * {@link RmiRegistry RMI registry} on publish MBeanServer onto.
052     */
053    @XmlElement
054    @XmlIDREF
055    @ImportService
056    private RmiRegistry rmiRegistry;
057
058    @Inject
059    private RmiRegistryPort portProvider;
060
061    @Inject
062    private MBeanServer mbeanServer;
063
064    @Override
065    public void start() {
066        JMXServiceURL url;
067        try {
068            url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + portProvider.getPort() + "/jmxrmi");
069        } catch (MalformedURLException e) {
070            throw new RuntimeException(e);
071        }
072
073        HashMap<String,Object> environment = new HashMap<>();
074        JMXConnectorServer connectorServer;
075        try {
076            connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mbeanServer);
077            connectorServer.start();
078        } catch (IOException e) {
079            throw new RuntimeException("Cannot start JMX connector server", e);
080        }
081    }
082}