Example usage for javax.management.remote JMXServiceURL JMXServiceURL

List of usage examples for javax.management.remote JMXServiceURL JMXServiceURL

Introduction

In this page you can find the example usage for javax.management.remote JMXServiceURL JMXServiceURL.

Prototype

public JMXServiceURL(String serviceURL) throws MalformedURLException 

Source Link

Document

Constructs a JMXServiceURL by parsing a Service URL string.

Usage

From source file:org.wso2.carbon.core.init.JMXServerManager.java

/**
 * The method to start JMX service./*from  w  w w .j av  a 2s .  co  m*/
 *
 * @throws ServerException If an error occurs while starting the RMI server
 */
public void startJMXService() throws ServerException {

    //File path for the jmx config file.
    String filePath = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "jmx.xml";
    boolean startJMXServer = false;

    File jmxConfigFile = new File(filePath);

    //Check whether jmx.xml file exists
    if (jmxConfigFile.exists()) {
        //Read jmx.xml file.
        parseJMXConfigXML(filePath);
        startJMXServer = jmxProperties.isStartServer();
        if (!startJMXServer) {
            return;
        }
    }

    int rmiRegistryPort = jmxProperties.getRmiRegistryPort();
    if (rmiRegistryPort == -1) {
        throw new RuntimeException(
                "RMIRegistry port has not been properly defined in the " + "jmx.xml or carbon.xml files");
    }
    MBeanServer mbs = ManagementFactory.getMBeanServer();
    String jmxURL;
    try {
        try {
            rmiRegistry = LocateRegistry.createRegistry(rmiRegistryPort);
        } catch (Throwable ignored) {
            log.error("Could not create the RMI local registry", ignored);
        }

        String hostName;
        //If 'startRMIServer' element in jmx.xml file set to true and 'HostName' element
        // value that file is not null.
        if (startJMXServer && jmxProperties.getHostName() != null) {
            hostName = jmxProperties.getHostName();//Set hostname value from jmx.xml file.
        } else { //Else
            hostName = NetworkUtils.getLocalHostname();
        }
        // Create an RMI connector and start it
        int rmiServerPort = jmxProperties.getRmiServerPort();
        if (rmiServerPort != -1) {
            jmxURL = "service:jmx:rmi://" + hostName + ":" + rmiServerPort + "/jndi/rmi://" + hostName + ":"
                    + rmiRegistryPort + "/jmxrmi";

        } else {
            jmxURL = "service:jmx:rmi:///jndi/rmi://" + hostName + ":" + rmiRegistryPort + "/jmxrmi";
        }
        JMXServiceURL url = new JMXServiceURL(jmxURL);

        // Security credentials are included in the env Map
        HashMap<String, CarbonJMXAuthenticator> env = new HashMap<String, CarbonJMXAuthenticator>();
        env.put(JMXConnectorServer.AUTHENTICATOR, new CarbonJMXAuthenticator());
        jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
        jmxConnectorServer.start();
        log.info("JMX Service URL  : " + jmxURL);
    } catch (Exception e) {
        String msg = "Could not initialize RMI server";
        log.error(msg, e);
    }
}

From source file:com.clustercontrol.jmx.factory.RunMonitorJmx.java

/**
 * JMX ??/* w  ww .j  a  v  a  2  s .  c om*/
 * 
 * @param facilityId ID
 * @return ???????true
 */
@Override
public boolean collect(String facilityId) {
    boolean result = false;

    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;
    exception = null;

    NodeInfo node = null;
    if (!m_isMonitorJob) {
        node = nodeInfo.get(facilityId);
    } else {
        try {
            // ??
            node = new RepositoryControllerBean().getNode(facilityId);
        } catch (Exception e) {
            m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES.getMessage();
            return false;
        }
    }

    JMXServiceURL url = null;
    try {
        String rmiFormat = HinemosPropertyUtil.getHinemosPropertyStr("monitor.jmx.rmi.format",
                "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi");
        String urlStr = String.format(rmiFormat, node.getAvailableIpAddress(), jmx.getPort());
        m_log.debug("facilityId=" + facilityId + ", url=" + urlStr);
        url = new JMXServiceURL(urlStr);
    } catch (Exception e) {
        m_log.warn("fail to initialize JMXServiceURL : " + e.getMessage() + " (" + e.getClass().getName() + ")",
                e);
        exception = e;
        return result;
    }

    JMXConnector jmxc = null;
    try {
        Map<String, Object> env = new HashMap<>();

        if (jmx.getAuthUser() != null)
            env.put(JMXConnector.CREDENTIALS, new String[] { jmx.getAuthUser(), jmx.getAuthPassword() });

        System.setProperty("sun.rmi.transport.tcp.responseTimeout", Integer.toString(HinemosPropertyUtil
                .getHinemosPropertyNum("system.sun.rmi.transport.tcp.responseTimeout", Long.valueOf(10 * 1000))
                .intValue()));
        jmxc = JMXConnectorFactory.connect(url, env);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        JmxMasterInfo jmxMasterInfo = QueryUtil.getJmxMasterInfoPK(jmx.getMasterId());
        Object value = mbsc.getAttribute(new ObjectName(jmxMasterInfo.getObjectName()),
                jmxMasterInfo.getAttributeName());
        m_value = Double.parseDouble(
                searchTargetValue(value, Arrays.asList(KeyParser.parseKeys(jmxMasterInfo.getKeys())))
                        .toString());

        // ??
        if (m_convertFlg == ConvertValueConstant.TYPE_DELTA) {

            // ??
            MonitorJmxValue valueEntity = null;
            Double prevValue = 0d;
            Long prevDate = 0l;

            if (!m_isMonitorJob) {
                // ??
                // cache??
                valueEntity = MonitorJmxCache.getMonitorJmxValue(m_monitorId, facilityId);

                // ???
                prevValue = valueEntity.getValue();
                if (valueEntity.getGetDate() != null) {
                    prevDate = valueEntity.getGetDate();
                }
            } else {
                // ??
                valueEntity = new MonitorJmxValue(new MonitorJmxValuePK(m_monitorId, facilityId));
                if (m_prvData instanceof MonitorJmxValue) {
                    // ????
                    prevValue = ((MonitorJmxValue) m_prvData).getValue();
                    prevDate = ((MonitorJmxValue) m_prvData).getGetDate();
                }
            }

            // JMX????
            valueEntity.setValue(Double.valueOf(m_value));
            valueEntity.setGetDate(m_nodeDate);

            if (!m_isMonitorJob) {
                // ???ID?????
                if (m_monitor.getMonitorFlg())
                    MonitorJmxCache.update(m_monitorId, facilityId, valueEntity);

                int m_validSecond = HinemosPropertyUtil
                        .getHinemosPropertyNum("monitor.jmx.valid.second", Long.valueOf(15)).intValue();
                // ???????????
                int tolerance = (m_runInterval + m_validSecond) * 1000;

                if (prevDate > m_nodeDate - tolerance) {

                    // ??null???
                    if (prevValue == null) {
                        m_log.debug("collect() : prevValue is null");
                        m_prevNullchk = true;
                        return false;
                    }

                    m_value = m_value - prevValue;
                } else {
                    if (prevDate != 0l) {
                        DateFormat df = DateFormat.getDateTimeInstance();
                        df.setTimeZone(HinemosTime.getTimeZone());
                        String[] args = { df.format(new Date(prevDate)) };
                        m_message = MessageConstant.MESSAGE_TOO_OLD_TO_CALCULATE.getMessage(args);
                        return false;
                    } else {
                        // ???0??
                        m_nodeDate = 0l;
                    }
                }
            } else {
                m_value = m_value - prevValue;
                m_curData = valueEntity;
            }
        }

        m_log.debug(jmxMasterInfo.getName() + " : " + m_value + " " + jmxMasterInfo.getMeasure());

        result = true;
    } catch (NumberFormatException e) {
        m_log.info("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        String[] args = { Double.toString(m_value) };
        m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NUMERIC_VALUE.getMessage(args);
        return false;
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null) {
            message = message.replaceAll("\n", "");
        }
        m_log.warn("fail to access JMXService : " + message + " (" + e.getClass().getName() + ")");
        exception = e;
    } finally {
        try {
            if (jmxc != null) {
                jmxc.close();
            }
        } catch (IOException e) {
            m_log.info("fail to close JMXService : " + e.getMessage() + " (" + e.getClass().getName() + ")");
            exception = e;
        }
    }

    return result;
}

From source file:org.lsc.webai.services.LscRemoteCommands.java

private boolean jmxBind() {
    if (lscServer != null) {
        try {/*from w w  w.j a  v a 2s  . c  om*/
            return lscServer.ping();
        } catch (UndeclaredThrowableException ce) {

        }
    }
    try {
        String sUrl = "service:jmx:rmi:///jndi/rmi://" + hostname + ":" + port + "/jmxrmi";
        LOGGER.info("Connecting to remote engine on : " + sUrl);
        url = new JMXServiceURL(sUrl);
        jmxC = new RMIConnector(url, null);
        jmxC.connect();
        jmxc = jmxC.getMBeanServerConnection();
        ObjectName lscServerName = new ObjectName("org.lsc.jmx:type=LscServer");
        lscServer = JMX.newMXBeanProxy(jmxc, lscServerName, LscServer.class, true);
        return true;
    } catch (MalformedObjectNameException e) {
        LOGGER.error(e.toString(), e);
    } catch (NullPointerException e) {
        LOGGER.error(e.toString(), e);
    } catch (MalformedURLException e) {
        LOGGER.error(e.toString(), e);
    } catch (IOException e) {
        if (!(e.getCause() instanceof ServiceUnavailableException)) {
            LOGGER.error(e.toString(), e);
        }
    }
    return false;
}

From source file:org.apache.cassandra.tools.AbstractJmxClient.java

private void connect() throws IOException {
    JMXServiceURL jmxUrl = new JMXServiceURL(String.format(FMT_URL, host, port));
    Map<String, Object> env = new HashMap<String, Object>();

    if (username != null)
        env.put(JMXConnector.CREDENTIALS, new String[] { username, password });

    jmxc = JMXConnectorFactory.connect(jmxUrl, env);
    mbeanServerConn = jmxc.getMBeanServerConnection();
}

From source file:org.apache.synapse.JmxAdapter.java

/**
 * Lazily creates the RMI registry and starts the JMX connector server based on the 
 *
 * @throws  SynapseException  if the JMX configuration is erroneous and/or the connector server
 *                            cannot be started
 *///from  ww  w  .j a  v  a2 s. c om
public void start() {
    initConfiguration();

    try {
        boolean registryCreated = false;
        int jndiPort = jmxInformation.getJndiPort();

        // automatic detection starting at base port
        if (jndiPort == 0) {
            jndiPort = JNDI_AUTO_PORT_OFFSET;
            for (int retries = 0; !registryCreated && (retries < 100); retries++) {
                try {
                    RMIRegistryController.getInstance().createLocalRegistry(jndiPort);
                    registryCreated = true;
                } catch (Exception ignored) {
                    jndiPort++;
                    log.warn("Trying alternate port " + jndiPort);
                }
            }
            jmxInformation.setJndiPort(jndiPort);
        } else {
            RMIRegistryController.getInstance().createLocalRegistry(jndiPort);
            registryCreated = true;
        }

        if (registryCreated) {
            jmxInformation.updateJMXUrl();
            JMXServiceURL url = new JMXServiceURL(jmxInformation.getJmxUrl());
            Map<String, Object> env = createContextMap();
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            try {
                connectorServer.start();
            } catch (IOException ex) {
                log.warn("Cannot start JMXConnectorServer on " + jmxInformation.getJmxUrl(), ex);
            }
        }
    } catch (Exception ex) {
        log.error("Error while setting up remote JMX connector", ex);
    }
}

From source file:fullThreadDump.java

private void connect(boolean jbossRemotingJMX, String hostname, String user, String passwd) {
    String urlString;/*from w w w .ja  v  a 2 s .c o m*/
    try {
        HashMap<String, String[]> env = new HashMap<String, String[]>();
        String[] creds = new String[2];
        creds[0] = user;
        creds[1] = passwd;
        env.put(JMXConnector.CREDENTIALS, creds);
        if (jbossRemotingJMX) {
            urlString = "service:jmx:remoting-jmx://" + hostname;
            this.serviceURL = new JMXServiceURL(urlString);
            System.out.println("\n\nConnecting to " + urlString);
        } else {
            urlString = "/jndi/rmi://" + hostname + "/jmxrmi";
            this.serviceURL = new JMXServiceURL("rmi", "", 0, urlString);
            System.out.println("\n\nConnecting to " + urlString);
        }

        //this.jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
        this.jmxConnector = JMXConnectorFactory.connect(serviceURL, env);
        this.server = jmxConnector.getMBeanServerConnection();
    } catch (MalformedURLException e) {
        // should not reach here
    } catch (IOException e) {
        System.err.println("\nCommunication error: " + e.getMessage());
        System.exit(1);
    }
}

From source file:org.rhq.plugins.cassandra.CassandraNodeComponent.java

private boolean isStorageServiceReachable() {
    JMXConnector connector = null;
    try {//from w  w w  .  ja  v  a2 s  .  com
        Configuration pluginConfig = getResourceContext().getPluginConfiguration();
        String url = pluginConfig.getSimpleValue("connectorAddress");
        JMXServiceURL serviceURL = new JMXServiceURL(url);
        connector = JMXConnectorFactory.connect(serviceURL, null);

        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");

        // query an attribute to make sure it is in fact available
        serverConnection.getAttribute(storageService, "NativeTransportRunning");

        return true;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to make JMX connection to StorageService", e);
        }
        return false;
    } finally {
        if (connector != null) {
            try {
                connector.close();
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("An error occurred closing the JMX connector", e);
                }
            }
        }
    }
}

From source file:com.zabbix.gateway.JMXItemChecker.java

public JMXItemChecker(JSONObject request) throws ZabbixException {
    super(request);

    try {//from   w  w  w  .j a va2s .co m
        String conn = request.getString(JSON_TAG_CONN);
        int port = request.getInt(JSON_TAG_PORT);

        jmxc = null;
        mbsc = null;
        String jmx_url = "service:jmx:rmi:///jndi/rmi://[" + conn + "]:" + port + "/jmxrmi"; // default
        String jboss_url = "service:jmx:remoting-jmx://" + conn + ":" + port; // jboss
        String t3_url = "service:jmx:t3://" + conn + ":" + port
                + "/jndi/weblogic.management.mbeanservers.runtime"; // T3
        String t3s_url = "service:jmx:t3s://" + conn + ":" + port
                + "/jndi/weblogic.management.mbeanservers.runtime"; // T3S
        protocol = "jmx";
        String tested_url = jmx_url;

        username = request.optString(JSON_TAG_USERNAME, null);
        password = request.optString(JSON_TAG_PASSWORD, null);

        //if (null != username && null == password || null == username && null != password)
        //   throw new IllegalArgumentException("invalid username and password nullness combination");

        if (null != username) {
            // Testing if username is like "<user>:<protocol>"
            int protocol_in_username = username.indexOf(':');
            if (protocol_in_username != -1) {
                String result[] = username.split(":");
                username = result[0];
                protocol = result[1];
            }
        }

        switch (protocol) {
        case "jmx":
        case "jmxs":
            tested_url = jmx_url;
            break;
        case "jboss":
            tested_url = jboss_url;
            break;
        case "t3":
            tested_url = t3_url;
            break;
        case "t3s":
            tested_url = t3s_url;
            break;
        default:
            tested_url = jmx_url;
            break;
        }

        logger.info("Using url '{}' with user '{}'", tested_url, username);

        HashMap<String, Object> env = new HashMap<String, Object>();
        env.put(JMXConnector.CREDENTIALS, new String[] { username, password });

        if (protocol.equals("t3") || protocol.equals("t3s")) {
            env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, ((String[]) env.get(JMXConnector.CREDENTIALS))[0]);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS,
                    ((String[]) env.get(JMXConnector.CREDENTIALS))[1]);
        }

        // Required by SSL
        if (protocol.equals("jmxs")) {
            env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
        }

        url = new JMXServiceURL(tested_url);
        jmxc = ZabbixJMXConnectorFactory.connect(url, env);
        mbsc = jmxc.getMBeanServerConnection();
    } catch (Exception e) {
        throw new ZabbixException(e);
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }
}

From source file:dk.netarkivet.common.utils.JMXUtils.java

/**
 * Constructs the same service URL that JConsole does
 * on the basis of a server name, a JMX port number,
 * and a RMI port number.//  ww w.  j a  v  a 2  s .c  o m
 *
 * Example URL:
 * service:jmx:rmi://0.0.0.0:9999/jndi/rmi://0.0.0.0:1099/JMXConnector
 * where RMI port number = 9999, JMX port number = 1099
 * server = 0.0.0.0 a.k.a localhost(?).
 *
 * @param server The server that should be connected to using
 * the constructed URL.
 * @param jmxPort The number of the JMX port that should be connected to
 * using the constructed URL (may not be a negative number)
 * @param rmiPort The number of the RMI port that should be connected to
 * using the constructed URL, or -1 if the default RMI port should be used.
 * @return the constructed URL.
 */
public static JMXServiceURL getUrl(String server, int jmxPort, int rmiPort) {
    ArgumentNotValid.checkNotNullOrEmpty(server, "String server");
    ArgumentNotValid.checkNotNegative(jmxPort, "int jmxPort");

    String url;
    if (rmiPort != -1) {
        url = "service:jmx:rmi://" + server + ":" + rmiPort + "/jndi/rmi://" + server + ":" + jmxPort
                + "/jmxrmi";
    } else {
        url = "service:jmx:rmi:///jndi/rmi://" + server + ":" + jmxPort + "/jmxrmi";
    }
    log.trace("Created url for JMX-connections: " + url);
    try {
        return new JMXServiceURL(url);
    } catch (MalformedURLException e) {
        throw new UnknownID("Could not create new JMXServiceURL from " + url, e);
    }
}

From source file:com.cognifide.aet.runner.util.MessagesManager.java

protected JMXConnector getJmxConnection(String jmxUrl) throws IOException {
    JMXServiceURL url = new JMXServiceURL(jmxUrl);
    return JMXConnectorFactory.connect(url);
}