

package gov.va.med.cds.client.functional.mbean;


import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Hashtable;

import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;


public class MBeanConnection
{
    private MBeanServerConnection connection;
    private JMXConnector connector;
    private ObjectName service;


    public void initConnection( String hostname, String portString, String username, String password, String serviceName )
        throws IOException,
            MalformedURLException,
            MalformedObjectNameException
    {
        String protocol = "t3";
        Integer portInteger = Integer.valueOf( portString );
        int port = portInteger.intValue();
        String jndiroot = "/jndi/";
        String mserver = "weblogic.management.mbeanservers.runtime";
        JMXServiceURL serviceURL = new JMXServiceURL( protocol, hostname, port, jndiroot + mserver );
        Hashtable<String, String> h = new Hashtable<String, String>();
        h.put( Context.SECURITY_PRINCIPAL, username );
        h.put( Context.SECURITY_CREDENTIALS, password );
        h.put( JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote" );
        connector = JMXConnectorFactory.connect( serviceURL, h );
        connection = connector.getMBeanServerConnection();
        service = new ObjectName( serviceName );
    }


    public MBeanServerConnection getConnection( )
    {
        return connection;
    }


    public ObjectName getService( )
    {
        return service;
    }


    public void closeConnection( )
        throws IOException
    {
        if ( connector != null )
        {
            connector.close();
        }
    }

}
