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.File;
019import java.io.IOException;
020import java.lang.management.ManagementFactory;
021
022import javax.management.remote.JMXConnector;
023import javax.management.remote.JMXConnectorFactory;
024import javax.management.remote.JMXServiceURL;
025
026import com.sun.tools.attach.AgentInitializationException;
027import com.sun.tools.attach.AgentLoadException;
028import com.sun.tools.attach.AttachNotSupportedException;
029import com.sun.tools.attach.VirtualMachine;
030
031public class JmxUtils {
032
033    public static long getVirtualMachinePid() {
034        String name = ManagementFactory.getRuntimeMXBean().getName();
035        return Long.parseLong(name.substring(0, name.indexOf('@')));
036    }
037
038    public static JMXServiceURL attachToJMX(Long pid) {
039        String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
040        VirtualMachine vm;
041        try {
042            vm = VirtualMachine.attach(pid.toString());
043        } catch (AttachNotSupportedException | IOException e) {
044            throw new RuntimeException(e);
045        }
046        try {
047            String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
048            if (connectorAddress == null) {
049                String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar";
050                vm.loadAgent(agent);
051                connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
052            }
053            return new JMXServiceURL(connectorAddress);
054        } catch (IOException | AgentLoadException | AgentInitializationException e) {
055            throw new RuntimeException(e);
056        } finally {
057            try {
058                vm.detach();
059            } catch (IOException e) {
060                throw new RuntimeException(e);
061            }
062        }
063    }
064
065    public static JMXConnector connectToItself() throws IOException {
066        return JMXConnectorFactory.connect(JmxUtils.attachToJMX(JmxUtils.getVirtualMachinePid()));
067    }
068
069}