/* 
 * @(#)GetPackageInfoAp.java 9/99
 *
 * Copyright (c) 09/20/99 Sun Microsystems, Inc.  All Rights Reserved.
 */

/*
This example is using  Solaris_Package CIM Object to demonstrates 
 - as to how to get properties and instance.
 - getCimClient: Connects to the CIM Object Manager and create a client instance
 - closeCimClient; Closes the client connection
 - getPkgNames: Gets the CIM Object Path, creates instance and gets properties.
 - getPkgInstance: Gets instance

solaris_package:
	root\cimv2
	->cim_managedsystemelement
	->cim_logicalelement
	->cim_softwareelement
	->solaris_package

*/
import java.awt.Graphics;

import java.rmi.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.event.*;
import com.sun.wbem.cim.*;
import com.sun.wbem.client.*;
import com.sun.wbem.security.UserPrincipal;
import com.sun.wbem.security.PasswordCredential;


public class GetPackageInfoAp extends JApplet implements ActionListener {
  
    public void init() {
        String[] pnInitList = { "  packages:       " };
        Container contentPane = getContentPane();
	contentPane.setLayout(new BorderLayout());
	// Text filed for the host name
	JPanel listPanel = new JPanel();
	JLabel hostLable = new JLabel("Host Name: ");
	listPanel.add(hostLable);
	hostFiled = new JTextField(19);
	hostFiled.setText("enter the host name and Return");
	hostFiled.addActionListener(this);
	listPanel.add(hostFiled);
	// Set up a lists of packages installed
	packages = makeList(pnInitList, 7);
	listPanel.add(new JScrollPane(packages));
	contentPane.add(listPanel, "North");
	// Add the checkboxes for selecting rmi/http(xml)
	JPanel checkBoxPanel = new JPanel();
	rmi = new JCheckBox("rmi");
	checkBoxPanel.add(rmi);
	rmi.setSelected(true);
	http = new JCheckBox("http");
	checkBoxPanel.add(http);
	contentPane.add(checkBoxPanel, "West");
        // Add the get instance button
	JPanel buttonPanel = new JPanel();
	getPkgButton = new JButton("Get package instance");
	getPkgButton.addActionListener(this);
	buttonPanel.add(getPkgButton);
	getPkgButton.setEnabled(false);
	contentPane.add(buttonPanel, "East");
	// Add the package info text area
	pkgInfo = new JTextArea(19, 95);
	pkgInfo.setFont(new Font("Courier", Font.PLAIN, 12));
	contentPane.add(new JScrollPane(pkgInfo), "South");
    }

    public void closeCimClient() {
        if (cc != null) {
	    try {
	        cc.close();
		cc = null;
	    } catch (Exception e) {
	        System.out.println("closeCimClient... Exception: "+e);
		showStatus("Exception: "+e.toString());
	    }
	}
    }

    /**
     *  Connecting to the CIM Object Manager
     *  A client application contacts a CIM Object Manager to establish a
     *  connection each time it needs to perform a WBEM operation.
     *  Use the CIMClient class to create an instance of the client
     *  on the CIM Object Manager.
     */
    public CIMClient getCimClient(String host, boolean httpChoise) {
	closeCimClient();
	try {
	    // Connect to CIM and get the CIM Client, select http/rmi chiose
	    cns = new CIMNameSpace(host);
	    if (httpChoise) {
	        showStatus
	    (cns+": Connecting to CIM Object Manager using HTTP protocol ... ");
		cc = new CIMClient(cns, (UserPrincipal) null,
			(PasswordCredential) null, CIMClient.HTTP);
	    } else {
	        showStatus
	    (cns+": Connecting to CIM Object Manager using RMI protocol ... ");
	        cc = new CIMClient(cns);
	    }
	} catch (Exception e) {
	    // e.printStackTrace();
	    System.out.println("getCimClient... Exception: "+e);
	    closeCimClient();
	    showStatus("Exception: "+e.toString());
	    pkgInfo.setText("");
	    getPkgButton.setEnabled(false);
	}
	return (cc);
    }

    /**
     *  Get the CIM Object Path of the Solaris_Package class, 
     *  The CIM Object Manager returns an enumeration of 
     *  object paths, the names of instances of the Solaris_Package class.
     *  Returns the property "Name" for each (instance) package.
     *  Another way to enumarate:
     *  Enumeration enum = cc.enumInstances(solarisPackageCOP,
     *                                      CIMClient.SHALLOW, false);
     *  while (enum.hasMoreElements()) {
     *      CIMInstance packageIE = (CIMInstance) enum.nextElement();
     *      nameList.addElement
     *          (packageIE.getProperty("Name").getValue().getValue());
     *  }
     * 
     */
    public Vector getPkgNames() {
	Vector nameList = new Vector();
	try {
	    // get object path and (enumerate) get property
	    showStatus
        (cns+": Solaris_Package class ... get instance properties (names)");
	    CIMObjectPath solarisPackageCOP = 
                               new CIMObjectPath("Solaris_Package");
	    Enumeration enum = cc.enumInstances(solarisPackageCOP, false);
	    // To speed up the process get just the 1st 15 packages
	    // To get all, replace the following line with this one
	    // for (int i=0; enum.hasMoreElements(); i++) {
	    for (int i = 0; i < 9; i++) {
	        CIMObjectPath pkgOP = (CIMObjectPath)enum.nextElement();
		CIMInstance packageIE = cc.getInstance(pkgOP, false);
		nameList.addElement
                    (packageIE.getProperty("Name").getValue().getValue());
	    }
	} catch (Exception e) {
	    System.out.println("getPkgNames... Exception: "+e);
	    showStatus("Exception: "+e.toString());
	    getPkgButton.setEnabled(false);
	    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	    return (null);
	}
	return (nameList);
    }

    /**  Get the package instance using the package property as a key */
    public void getPkgInstance(String packageName) {
        try {
	    // set up keys for solaris processor
 	    Vector processorKeys = new Vector();

	    CIMProperty processorKey = new CIMProperty("Name");
	    processorKey.setType
	            (CIMDataType.getPredefinedType(CIMDataType.STRING));
	    processorKey.setValue(new CIMValue(packageName));
	    processorKeys.addElement(processorKey);
	    // get handle to solaris_package
	    CIMObjectPath solarisPackageCOP = 
                new CIMObjectPath("Solaris_Package", processorKeys);
	    CIMInstance packageIE = cc.getInstance(solarisPackageCOP, false);
            pkgInfo.append(packageIE + "\n");
	} catch (Exception e) {
	    System.out.println("getPkgInstance... Exception: "+e);
	    showStatus("Exception: "+e.toString());
	}
    }

    public String getItem(JList list, String[] items) {
        return items[list.getSelectedIndex()];
    }

    public void actionPerformed(ActionEvent evt) {
        String host;
	Vector vList;
        if (evt.getSource() == hostFiled) {
	    setCursor(new Cursor(Cursor.WAIT_CURSOR));
	    pkgInfo.setText("");
	    boolean httpSelect = false;
	    if (rmi.isSelected()) 
	        http.setSelected(false); 
	    if (http.isSelected()) 
	        httpSelect = true; 
	    else 
	        rmi.setSelected(true);
	    // Get CIM Client
	    if (getCimClient(host = evt.getActionCommand(), httpSelect)
		                                            != null) {
		// Get object property (list of package names)
		if ((vList = getPkgNames()) == null)
		    return;
		pkgNamesArray = new String[vList.size()];
		if (vList.size() != 0)
		    vList.copyInto(pkgNamesArray);
		packages.setListData(pkgNamesArray);
		packages.setSelectedIndex(0);
		getPkgButton.setEnabled(true);
	        rmi.setEnabled(false);
	        http.setEnabled(false);
	    }
	    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	    return;
	}
	showStatus(cns+": Geting Solaris_Package instance (pkginfo): ... ");
        getPkgInstance(getItem(packages, pkgNamesArray));
    }

    public JList makeList(final String[] items, int visibleRows) {
        JList list = new JList(new AbstractListModel() {
	    public Object getElementAt(int i) {
                return items[i];
	    }

	    public int getSize() {
	        return items.length;
	    }
        });
	list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	list.setVisibleRowCount(visibleRows);
	list.setSelectedIndex(0);
	return list;
    }

    private CIMNameSpace cns;
    private CIMClient cc;

    private JCheckBox rmi;
    private JCheckBox http;
    private JButton getPkgButton;
    private JTextField hostFiled;
    private JList packages;
    private JTextArea pkgInfo;
    private String[] pkgNamesArray;
}
