Ejemplo: programa de cliente administrativo

Los ejemplos siguientes son un programa cliente administrativo completo. Los segundos ejemplos utilizan un conector RMI (invocación a método remoto).

En ambos ejemplos se muestra cómo conectar con el servidor del agente de nodo, que no está disponible para su producto. No obstante, puede conectarse con el servidor modificando los valores de host y de puerto. Sustituya las referencias de su servidor para el servidor del agente de nodo. Dado que el MBean NodeAgent no está disponible para su producto, sustituya la serie queryNames para buscar otro MBean.

Copie el contenido a un archivo llamado AdminClientExample.java. Después de cambiar el nombre de nodo y de servidor a los valores adecuados para su configuración, puede compilarlo y ejecutarlo utilizando las instrucciones de Creación de un programa cliente administrativo Java personalizado mediante las API administrativas de Java de WebSphere Application Server

import java.util.Date; 
import java.util.Properties;
import java.util.Set;

import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;

import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
import com.ibm.websphere.management.exception.ConnectorException;

public class AdminClientExampleSoap implements NotificationListener
{

    private AdminClient adminClient;
    private ObjectName nodeAgent;
    private long ntfyCount = 0;

    public static void main(String[] args)
    {
       AdminClientExampleSoap ace = new AdminClientExampleSoap();

       // Crear un AdminClient
       ace.createAdminClient();

       // Encontrar un NodeAgent MBean
       ace.getNodeAgentMBean("timmieNode07");

       // Invocar a launchProcess
       ace.invokeLaunchProcess("server1");

       // Registrar los sucesos de NodeAgent
       ace.registerNotificationListener();

       // Ejecutar hasta que se interrumpa
       ace.countNotifications();
    }

    private void createAdminClient()
    {
        // Establecer un objeto Properties para los atributos del conector JMX
        Properties connectProps = new Properties();
        connectProps.setProperty(
        AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
        connectProps.setProperty(AdminClient.CONNECTOR_HOST, "timmie");
        connectProps.setProperty(AdminClient.CONNECTOR_PORT, "8886");
        System.setProperty("com.ibm.SSL.ConfigURL", "file:C:/MyThinClient/70properties/ssl.client.props");
        System.setProperty("com.ibm.SOAP.ConfigURL", "file:C:/MyThinClient/70properties/soap.client.props");

        // Obtener un AdminClient basándose en las propiedades del conector
        try
        {
            adminClient = AdminClientFactory.createAdminClient(connectProps);
        }
        catch (ConnectorException e)
        {
            System.out.println("Excepción al crear el cliente de administración: " + e);
            System.exit(-1);
        }

        System.out.println("Conectado a DeploymentManager");
    }


    private void getNodeAgentMBean(String nodeName)
    {
        // Consultar el ObjectName del NodeAgent MBean en el nodo especificado
        try
        {
            String query = "WebSphere:type=NodeAgent,node=" + nodeName + ",*";
            ObjectName queryName = new ObjectName(query);
            Set s = adminClient.queryNames(queryName, null);
            if (!s.isEmpty())
                nodeAgent = (ObjectName)s.iterator().next();
            else
            {
                System.out.println("No se ha encontrado el MBean del agente de
nodo");
                System.exit(-1);
            }
        }
        catch (MalformedObjectNameException e)
        {
            System.out.println(e);
            System.exit(-1);
        }
        catch (ConnectorException e)
        {
            System.out.println(e);
            System.exit(-1);
        } catch(Exception e) {
        	e.printStackTrace();
            System.exit(-1);
        }

        System.out.println("Found NodeAgent MBean for node " + nodeName);
    }

    private void invokeLaunchProcess(String serverName)
    {
        // Utilizar la operación launchProcess en el NodeAgent MBean para iniciar
        // el servidor especificado
        String opName = "launchProcess";
        String signature[] = { "java.lang.String" };
        String params[] = { serverName };
        boolean launched = false;
        try
        {
            Boolean b = (Boolean)adminClient.invoke(nodeAgent, opName, params, signature);
            launched = b.booleanValue();
            if (launched)
                System.out.println(serverName + " was launched");
            else
                System.out.println(serverName + " was not launched");

        }
        catch (Exception e)
        {
            System.out.println("Excepción al invocar launchProcess: " + e);
        }
    }

    private void registerNotificationListener()
    {
        // Registrar este objeto como un receptor para notificaciones del
        // NodeAgent MBean.  No utilizar un filtro ni un objeto
        // handback.
        try
        {
            adminClient.addNotificationListener(nodeAgent, this, null, null);
            System.out.println("Registered for event notifications");
        }
        catch (InstanceNotFoundException e)
        {
            System.out.println(e);
        }
        catch (ConnectorException e)
        {
            System.out.println(e);
        }
    }

    public void handleNotification(Notification ntfyObj, Object handback)
    {
        // Cada notificación que genera el NodeAgent MBean provocará que
        // se llame a este método
        ntfyCount++;
        System.out.println("***************************************************");
        System.out.println("* Notification received at " + new Date().toString());
        System.out.println("* type      = " + ntfyObj.getType());
        System.out.println("* message   = " + ntfyObj.getMessage());
        System.out.println("* source    = " + ntfyObj.getSource());
        System.out.println("* seqNum    = " + Long.toString(ntfyObj.getSequenceNumber()));
        System.out.println("* timeStamp = " + new Date(ntfyObj.getTimeStamp()));
        System.out.println("* userData  = " + ntfyObj.getUserData());
        System.out.println("***************************************************");

    }

    private void countNotifications()
    {
        // Ejecutar hasta que se interrumpa
        try
        {
            while (true)
            {
                Thread.currentThread().sleep(60000);
                System.out.println(ntfyCount + " notification have been received");
            }
        }
        catch (InterruptedException e)
        {
        }
    }

}

En el ejemplo siguiente se utiliza un conector RMI. El tipo de conector y el valor de puerto son diferentes de lo que se muestra en el ejemplo anterior.

import java.util.Date; 
import java.util.Properties;
import java.util.Set;

import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;

import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
import com.ibm.websphere.management.exception.ConnectorException;

public class AdminClientExampleSoap implements NotificationListener
{

    private AdminClient adminClient;
    private ObjectName nodeAgent;
    private long ntfyCount = 0;

    public static void main(String[] args)
    {
       AdminClientExampleSoap ace = new AdminClientExampleSoap();

       // Crear un AdminClient
       ace.createAdminClient();

       // Encontrar un NodeAgent MBean
       ace.getNodeAgentMBean("timmieNode07");

       // Invocar a launchProcess
       ace.invokeLaunchProcess("server1");

       // Registrar los sucesos de NodeAgent
       ace.registerNotificationListener();

       // Ejecutar hasta que se interrumpa
       ace.countNotifications();
    }

    private void createAdminClient()
    {
        // Establecer un objeto Properties para los atributos del conector JMX
        Properties connectProps = new Properties();
        connectProps.setProperty(
        AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
        connectProps.setProperty(AdminClient.CONNECTOR_HOST, "timmie");
        connectProps.setProperty(AdminClient.CONNECTOR_PORT, "8886");
        System.setProperty("com.ibm.SSL.ConfigURL", "file:C:/MyThinClient/70properties/ssl.client.props");
        System.setProperty("com.ibm.SOAP.ConfigURL", "file:C:/MyThinClient/70properties/soap.client.props");

        // Obtener un AdminClient basándose en las propiedades del conector
        try
        {
            adminClient = AdminClientFactory.createAdminClient(connectProps);
        }
        catch (ConnectorException e)
        {
            System.out.println("Excepción al crear el cliente de administración: " + e);
            System.exit(-1);
        }

        System.out.println("Conectado a DeploymentManager");
    }


    private void getNodeAgentMBean(String nodeName)
    {
        // Consultar el ObjectName del NodeAgent MBean en el nodo especificado
        try
        {
            String query = "WebSphere:type=NodeAgent,node=" + nodeName + ",*";
            ObjectName queryName = new ObjectName(query);
            Set s = adminClient.queryNames(queryName, null);
            if (!s.isEmpty())
                nodeAgent = (ObjectName)s.iterator().next();
            else
            {
                System.out.println("No se ha encontrado el MBean del agente de
nodo");
                System.exit(-1);
            }
        }
        catch (MalformedObjectNameException e)
        {
            System.out.println(e);
            System.exit(-1);
        }
        catch (ConnectorException e)
        {
            System.out.println(e);
            System.exit(-1);
        } catch(Exception e) {
        	e.printStackTrace();
            System.exit(-1);
        }

        System.out.println("Found NodeAgent MBean for node " + nodeName);
    }

    private void invokeLaunchProcess(String serverName)
    {
        // Utilizar la operación launchProcess en el NodeAgent MBean para iniciar
        // el servidor especificado
        String opName = "launchProcess";
        String signature[] = { "java.lang.String" };
        String params[] = { serverName };
        boolean launched = false;
        try
        {
            Boolean b = (Boolean)adminClient.invoke(nodeAgent, opName, params, signature);
            launched = b.booleanValue();
            if (launched)
                System.out.println(serverName + " was launched");
            else
                System.out.println(serverName + " was not launched");

        }
        catch (Exception e)
        {
            System.out.println("Excepción al invocar launchProcess: " + e);
        }
    }

    private void registerNotificationListener()
    {
        // Registrar este objeto como un receptor para notificaciones del
        // NodeAgent MBean.  No utilizar un filtro ni un objeto
        // handback.
        try
        {
            adminClient.addNotificationListener(nodeAgent, this, null, null);
            System.out.println("Registered for event notifications");
        }
        catch (InstanceNotFoundException e)
        {
            System.out.println(e);
        }
        catch (ConnectorException e)
        {
            System.out.println(e);
        }
    }

    public void handleNotification(Notification ntfyObj, Object handback)
    {
        // Cada notificación que genera el NodeAgent MBean provocará que
        // se llame a este método
        ntfyCount++;
        System.out.println("***************************************************");
        System.out.println("* Notification received at " + new Date().toString());
        System.out.println("* type      = " + ntfyObj.getType());
        System.out.println("* message   = " + ntfyObj.getMessage());
        System.out.println("* source    = " + ntfyObj.getSource());
        System.out.println("* seqNum    = " + Long.toString(ntfyObj.getSequenceNumber()));
        System.out.println("* timeStamp = " + new Date(ntfyObj.getTimeStamp()));
        System.out.println("* userData  = " + ntfyObj.getUserData());
        System.out.println("***************************************************");

    }

    private void countNotifications()
    {
        // Ejecutar hasta que se interrumpa
        try
        {
            while (true)
            {
                Thread.currentThread().sleep(60000);
                System.out.println(ntfyCount + " notification have been received");
            }
        }
        catch (InterruptedException e)
        {
        }
    }

}

Icon that indicates the type of topic Reference topic



Timestamp icon Last updated: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-base-dist&topic=rjmx_adminclient
File name: rjmx_adminclient.html