# $Id: WBEM.pm,v 1.2 2004/11/18 18:00:46 jkremer Exp $
# Copyright 2004, Sun Microsystems, Inc. All rights reserved.
package Java::WBEM;

use Java::JrexMsg;
use Java::JrexClient;
use System;
use Debug;
use strict;

# Usage:
# my $cimom = new Java::WBEM();
# $cimom->openClient();
# my $instances = $cimom->enumInstances("CIM_DiskDrive");
# my $error     = $cimom->getError();
# if ($error){
#   print "Error ".$error->{error} . "in java code.";
#   print "Java stack trace ". $error->{trace} . "\n";
# }
# foreach $disk (@$instances){
#    my $id = $disk->{DeviceId};
# }
# $cimom->closeClient();

sub new {
  my ($class, $host, $user, $pass) = @_;

  if ( (!$user) && (!$pass)){
	 #
	 # Set effective user to admin.
	 # JVM already runs as noaccess.  Todo add user param to JVM launch
    # but since noaccess works we are good to go.
	 #my $adminId = getpwnam ('admin');
	 #$> = $adminId;
	 #$< = $adminId;
  }
  my $this = { 
				  client => new Java::JrexClient(),
				  host   => $host,
				  user   => $user,
				  pass   => $pass
				 };
  bless ($this, "Java::WBEM");
  return $this;
}

sub getError {
  my ($this, $className) = @_;
  my $client = $this->{client};
  my $wbem = $this->{wbem};

  return $wbem->getError();
}

sub enumInstances {
  my ($this, $className) = @_;
  my $wbem = $this->{wbem};

  return $wbem->enumInstances($className);
}

sub getNameSpaces {
  my ($this, $rootNS) = @_;
  my $wbem = $this->{wbem};
  $rootNS = "/root/cimv2" if (!$rootNS);
  return $wbem->getNameSpaces($rootNS);
}

sub getCIMClient {
  my ($this) = @_;
  return $this->{wbem};
}

sub openClient {
  my ($this, $namespace) = @_;
  my $client = $this->{client};
  $client->openSession();

  my $wbem;
  if ($this->{host} && (!("localhost" eq $this->{host}))){
	 $wbem = $client->createObject
	 ("com.sun.netstorage.fm.wbem.client.WBEMClient",
	  [$this->{host}, $namespace, $this->{user}, $this->{pass}]
	  );
  } else {
	 $wbem = $client->createObject
		("com.sun.netstorage.fm.wbem.client.WBEMClient", [$namespace],
		 ["java.lang.String"]);
  }

  $this->{wbem} = $wbem;

  eval {
	 $wbem->connect();
  };
  if ($@){
	 return $@;
  }
}

sub closeClient {
  my ($this) = @_;
  my $client = $this->{client};
  my $wbem = $this->{wbem};

  if ($client){
	 if ($wbem){
		$client->invoke($wbem, "close");
	 }
	 $client->closeSession();
  }
}

1;
