Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, October 13, 2008

Random Password Generator

A lot of places we need to create and apply Random Password upon granting a resource or creation of OIM user via code. Here is a code that would generate one and will also allow you to specify the length of random password.

================================
RandomPasswordGenerator.java
================================

import java.util.Random;

public class RandomPasswordGenerator {

public static int DEFAULT_PASSWORD_LENGTH=8;
public static char[] Special_Character = {'!','@','#','$','%','^','&','*','(',')' };
public static char getSpecialCharacter(){
Random rand = new Random();
int randInt = rand.nextInt(10);
return Special_Character[randInt];
}

public static String getPassword(int n) {
if(n <=8 ){
n=DEFAULT_PASSWORD_LENGTH;
}
char[] pw = new char[n];
int c = 'A';
int r1 = 0;
int i=0;
String tempString = new String();
while(i< n){
r1 = (int)(Math.random() * 4);
l1: switch(r1) {
case 0: c = '0' + (int)(Math.random() * 10); break l1;
case 1: c = 'a' + (int)(Math.random() * 26); break l1;
case 2: c = 'A' + (int)(Math.random() * 26); break l1;
case 3: c = getSpecialCharacter(); break;
}

char c1 = (char)c;
boolean isExisting = false;
l2: for(int j=0; j < i; j++){
if(c1 == pw[j]){
isExisting = true;
break l2;
}
}
if(!isExisting){
pw[i] = (char)c;
i++;
}

}
return new String(pw);
}
public static void main(String args[]){
System.out.println(RandomPasswordGenerator.getPassword(8));
}
}

===============================
Output would be something like:
===============================
&3FVZfxb

Wednesday, January 23, 2008

Creating Scheduled Task Event

If you need to do create a schedule task event that occurs periodically in OIM, here is a code snippet that you can modify to put your custom task in.

In my example here, I am emailing all the members of a OIM Group "Blank Email ID Notification" (configurable - passed from task scheduler itself) to notify that there are Employees in OIM with Blank Employee IDs. Someone should log on to OIM and add employee user ids. This can be a task that can run daily, weekly, monthly or however you want to configure it within OIM. Just create the jar file from the code and drop it in ScheduledTask folder under xellerate application.

======================================
Here is how to configure the task scheduler and OIM group:
======================================






======================================
Here is how the end result looks :
======================================




======================================
BlankEIDEmail.java
======================================

import java.util.HashMap;

import com.thortech.xl.scheduler.tasks.SchedulerBaseTask;
import Thor.API.tcResultSet;
import Thor.API.Operations.tcUserOperationsIntf;
import Thor.API.Operations.tcGroupOperationsIntf;
import com.thortech.xl.dataobj.util.tcEmailNotificationUtil;

/**
*
* Class to determine the OIM users having a blank EID
*
*/

public class BlankEIDEmail extends SchedulerBaseTask{

private tcUserOperationsIntf userAPI;
private String eid;
private String userID;
private String firstName;
private String middleName;
private String lastName;
private String dept;
private String manager;
private String mailBody;
private String mailTemp;
public static String newline = "\n\r";
private String grpName;
private tcGroupOperationsIntf grpAPI;

public void init() {
//Fetch the attributes of the scheduled task and initialize the APIs
try{
grpName = getAttribute("Group Name");
mailTemp = getAttribute("Email Template");
userAPI = (tcUserOperationsIntf)getUtility("Thor.API.Operations.tcUserOperationsIntf");
grpAPI = (tcGroupOperationsIntf)getUtility("Thor.API.Operations.tcGroupOperationsIntf");
}
catch(Exception e){
e.printStackTrace();
}
}//end of init method

public void execute() {
try{
HashMap hashmap = new HashMap();
hashmap.put("Users.User ID","*");
//hashmap.put("USR_UDF_EID", "");
tcResultSet rset = userAPI.findAllUsers(hashmap);
System.out.println("** Filtered ** Number of Users:"+rset.getRowCount());
rset.sort("USR_UDF_EID",true);
if(rset.getRowCount()>0){
mailBody = "The following users have a blank EID:"+newline;
mailBody+= "(First Name, Middle Name, Last Name, User ID, Manager, Department)"+newline;
for(int count=0;count rset.goToRow(count);
eid = rset.getStringValue("USR_UDF_EID");
System.out.println("Processing User:"+rset.getStringValue("Users.User ID")+";USR_UDF_EID="+eid);
//filter users who have a blank EID
if(eid =="" eid==null){
userID = rset.getStringValue("Users.User ID");
firstName = rset.getStringValue("Users.First Name");
middleName = rset.getStringValue("Users.Middle Name");
lastName = rset.getStringValue("Users.Last Name");
manager = rset.getStringValue("Users.Manager Login");
dept = rset.getStringValue("USR_UDF_DEPARTMENT");
mailBody+= firstName+", ";
mailBody+= middleName+", ";
mailBody+= lastName+", ";
mailBody+= userID+", ";
mailBody+= manager+",";
mailBody+= dept;
mailBody+= newline;
}///end of inner if
else{
break;
}//end of inner else
}//end of for loop */
mailBody+=newline;
mailBody+="Thank You."+newline;
mailBody+="System Administrator."+newline;
mailTo(mailBody);
}//end of outer if
else{
}//end of else
}//end of try block
catch(Exception e){
e.printStackTrace();
}//end of catch block
}//end of execute method


public void mailTo(String mailBody)
{
try
{
tcEmailNotificationUtil sendMail = new tcEmailNotificationUtil(getDataBase());
//construct the email text
sendMail.constructEmail(mailTemp);
sendMail.setBody(mailBody);
tcResultSet memberSet = getGroupMembers(grpName);
for(int i=0;i memberSet.goToRow(i);
String usrID = memberSet.getStringValue("Users.User ID");
HashMap findUsr = new HashMap();
findUsr.put("Users.User ID", usrID);
tcResultSet userSet = userAPI.findUsers(findUsr);
String reqMailID = userSet.getStringValue("Users.Email");
//send email to the respective user ids
if(reqMailID =="" reqMailID==null){
System.out.println("Blank email for UserID:"+usrID);
} else {
System.out.println("Mailing BlankEID List to:"+reqMailID);
sendMail.sendEmail(reqMailID);
}
}//end of for loop
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* This method is called to find one the members of a group
* @param name of the group
* @return returns resultset containing members of the group
*/

public tcResultSet getGroupMembers(String groupName){
tcResultSet grpMembers = null;
try{
HashMap grp = new HashMap();
grp.put("Groups.Group Name", grpName);
tcResultSet groupSet = grpAPI.findGroups(grp);
groupSet = grpAPI.findGroups(grp);
long grpKey = groupSet.getLongValue("Groups.Key");
grpMembers = grpAPI.getAllMemberUsers(grpKey);
}
catch(Exception e){
e.printStackTrace();
}
return grpMembers;
}
}

Thursday, January 17, 2008

Kerberos Authentication

You may use the following code to implement Kerberos Authentication in your applications:

====================================
CompanyKerbLogin.conf
====================================

/**
* Login Configuration for JAAS.
*
* Specify that Kerberos v5 is a required login module for the classes.
*/

CompanyKerbCallbackHandler {
com.sun.security.auth.module.Krb5LoginModule
required
client=TRUE
debug=FALSE
useTicketCache=FALSE;
};

====================================
krb5.conf
====================================

[domain_realms]

.bhatia.company.com = BHATIA.COMPANY.COM
.company.com=COMPANY.COM
bhatia.company.com = BHATIA.COMPANY.COM
company.com=COMPANY.COM


[libdefaults]

default_realm = COMPANY.COM
#dns_lookup_kdc=false
#default_tgs_enctypes = des-cbc-md5
#default_tkt_enctypes = des-cbc-md5


[logging]



[realms]
BHATIA.COMPANY.COM= {
kdc = server2.bhatia.company.com
admin_server = server2.bhatia.company.com
default_domain = bhatia.company.com
}

COMPANY.COM= {
kdc = server01.company.com
admin_server = server01.company.com
default_domain = company.com
}

import javax.security.auth.callback.*;

====================================
CompanyKerbCallbackHandler.java
====================================

/**
* Callback Handler that is used with the KerberosAuthHandler.
*
* Two methods are added to this callback handler which allows the
* KerberosAuthHandler to pass the username and password received
*
*/
public class CompanyKerbCallbackHandler implements CallbackHandler
{

private String CompanyUserId;
private char [] CompanyPassword;

public void handle(Callback[] callbacks)
throws java.io.IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback cb = (NameCallback)callbacks[i];
cb.setName(CompanyUserId);

} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback cb = (PasswordCallback)callbacks[i];
cb.setPassword(CompanyPassword);

} else {
throw new UnsupportedCallbackException(callbacks[i]);
}
}
}

public void setUserId(String userid)
{
CompanyUserId = userid;
}

public void setPassword(String password)
{
CompanyPassword = password.toCharArray();
}
}

This should do the magic for you !! Enjoy Authenticating.

Friday, October 19, 2007

Implementing SHA encryption to secure data

Here I provide you with a class that will assist you to have a Base64 encoding of your data.
==============================
Base64coder.java
==============================
public class Base64Coder {

// Mapping table from 6-bit nibbles to Base64 characters.
private static char[] map1 = new char[64];
static {
int i=0;
for (char c='A'; c<='Z'; c++) map1[i++] = c;
for (char c='a'; c<='z'; c++) map1[i++] = c;
for (char c='0'; c<='9'; c++) map1[i++] = c;
map1[i++] = '+'; map1[i++] = '/'; }

// Mapping table from Base64 characters to 6-bit nibbles.
private static byte[] map2 = new byte[128];
static {
for (int i=0; i < map2.length; i++) map2[i] = -1;
for (int i=0; i < 64; i++) map2[map1[i]] = (byte)i; }

/**
* Encodes a string into Base64 format.
* No blanks or line breaks are inserted.
* @param s a String to be encoded.
* @return A String with the Base64 encoded data.
*/
public static String encodeString (String s) {
return new String(encode(s.getBytes())); }

/**
* Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted.
* @param in an array containing the data bytes to be encoded.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode (byte[] in) {
return encode(in,in.length); }

/**
* Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted.
* @param in an array containing the data bytes to be encoded.
* @param iLen number of bytes to process in in.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode (byte[] in, int iLen) {
int oDataLen = (iLen*4+2)/3; // output length without padding
int oLen = ((iLen+2)/3)*4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '='; op++;
out[op] = op < oDataLen ? map1[o3] : '='; op++; }
return out; }

/**
* Decodes a string from Base64 format.
* @param s a Base64 String to be decoded.
* @return A String containing the decoded data.
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public static String decodeString (String s) {
return new String(decode(s)); }

/**
* Decodes a byte array from Base64 format.
* @param s a Base64 String to be decoded.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public static byte[] decode (String s) {
return decode(s.toCharArray()); }

/**
* Decodes a byte array from Base64 format.
* No blanks or line breaks are allowed within the Base64 encoded data.
* @param in a character array containing the Base64 encoded data.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public static byte[] decode (char[] in) {
int iLen = in.length;
if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
while (iLen > 0 && in[iLen-1] == '=') iLen--;
int oLen = (iLen*3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : 'A';
int i3 = ip < iLen ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
int o0 = ( b0 <<2) | (b1>>>4);
int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
int o2 = ((b2 & 3)<<6) | b3;
out[op++] = (byte)o0;
if (op < oLen) out[op++] = (byte)o1;
if (op < oLen) out[op++] = (byte)o2; }
return out; }

// Dummy constructor.
private Base64Coder() {}

} // end class Base64Coder


===============================
DigestService.java
===============================

import java.security.MessageDigest;

public final class DigestService
{
public static String encrypt(String plaintext) throws Exception {

MessageDigest md = MessageDigest.getInstance("SHA");

md.update(plaintext.getBytes("UTF-8"));

return new String(Base64Coder.encode(md.digest()));
}
}

================================
Base64Test.java
================================

public class Base64Test {

public static void main(String[] args) {
try{
System.out.println(DigestService.encrypt("rajnishbhatia19"));
}catch(Exception ex){
ex.printStackTrace();
}
}

}

========================
Results:
========================
OA4WNjP6mo9Yw12bDET5ZutjOC4=

Tuesday, September 4, 2007

Implementing Sun RSA CRT Security to secure data

Often times you need to encrypt/cipher data to keep in your datastores in a non human readable format. There are various ways to achieve this and one of the ways is to implement asymmetric encryption or commonly known as key/pair implementation. Key Pair term is used because this implementation involves a pair of distributable Public Keys and a secret Private key. Data Encrypted by your Public Key can only be decrypted by your Private Key. Longer Keys provide stronger encryption but it requires more computation and hence not appropriate for large amounts of data. You may use it to secure small but important data like credentials, social-security numbers etc. The algorithm used in this secure implementation is Chinese Remainder Theorem (CRT) and it is patented by RSA.

Here, I present you a way to implement this into your apps:

=================================================
KeyGen.java
=================================================

import java.security.KeyPair;
import java.security.KeyPairGenerator;

public class KeyGen {

public static void main(String[] args) throws Exception {
String algorithm = "RSA";
KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
generator.initialize(1024);
KeyPair keyPair = generator.generateKeyPair();
System.out.println(keyPair.getClass().getName());
System.out.println(keyPair.getPublic().getClass().getName());
System.out.println(keyPair.getPublic());
System.out.println(keyPair.getPrivate());
}

}
=========================
Results:
=========================
java.security.KeyPair

sun.security.rsa.RSAPublicKeyImpl


Sun RSA public key, 1024 bits
modulus: 98677203744446260465542414765650691002275163600893336774030639809055241671590316795866062624226355106366106365150146141568384880010496063021240945844297495973945754466316385920919706173968448314515263558835923413988948374505246140063606334219872299586481788510932872327106443573840159515004641256381252312213
public exponent: 65537


Sun RSA private CRT key, 1024 bits
modulus: 98677203744446260465542414765650691002275163600893336774030639809055241671590316795866062624226355106366106365150146141568384880010496063021240945844297495973945754466316385920919706173968448314515263558835923413988948374505246140063606334219872299586481788510932872327106443573840159515004641256381252312213
public exponent: 65537
private exponent: 66010151355116476266381509769151653939465423309378897073565730501377708014162855770748799174644973590768519601973656972282825907877079480277007252494924174792809949607545280699010499959716736392703906869830507078213365818919271289454064367852372369106548543273821152999734305850287488981430290809005791015693
prime p: 11233688489962973338844802243855066309619057073058245210667885044580710403537025877181943919444268451387897571270403920077238069995990276143846449096478403
prime q: 8784043089018529857113045198094546951702263784704005736527840877045442563172893548671083896835744209733189342603630638586802678054189266328008006731555271
prime exponent p: 8735389670346415723853835420469992359595440538279052938432591629795720945192088633183487587511158716749775486016789364404476959933101247430347784287573925
prime exponent q: 7568240491089313012675972506455997195093153895770273096400217632226802566063759511714930853086457002102541608853878078618832110395774159825400920214596333
crt coefficient: 7682099122771530487734293443893764412335043357041532111008506208973843014546928432001347862281087160360054782853678831202444919205277659896883572013566175

=================================================
PasswordEncrypt.java
=================================================

import java.math.BigInteger;
import java.security.PublicKey;

import javax.crypto.Cipher;

import org.apache.axis.encoding.Base64;

import sun.security.rsa.RSAPublicKeyImpl;

public class PasswordEncrypt {

private static BigInteger mod;
private static BigInteger pubExp;
private static PublicKey key;
private static Cipher cipher;

static
{
try
{
mod = new BigInteger("98677203744446260465542414765650691002275163600893336774030639809055241671590316795866062624226355106366106365150146141568384880010496063021240945844297495973945754466316385920919706173968448314515263558835923413988948374505246140063606334219872299586481788510932872327106443573840159515004641256381252312213", 10);
pubExp = new BigInteger("65537", 10);

key = new RSAPublicKeyImpl(mod, pubExp);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}

public PasswordEncrypt()
{
super();
}

public static String encrypt(String password) throws Exception
{
// encrypt the password
byte[] data = password.getBytes();
data = cipher.doFinal(data);
return new String(Base64.encode(data));
}

public static void main(String[] args)
{
try{
System.out.println(encrypt("test"));
}catch(Exception ex){System.out.println(ex.getStackTrace());}
}
}

========================
Results:
========================

iMeOizw/O75tdjDSzXSlkUCGahuNYSvhc5oW/jKzV7+hS6eaxtWzbhcssgAd4ygxGbBL3gZxzxEVePRfLedFPqX/DAHMKSVbeCqbtE+1TtHjvIo46SReAahNANvDJnAXmCO2Bp4p+l4hGrTCAz9EXkhUQdel6AIc0DwJOSB0I+4=

=================================================
PasswordDecrypt.java
=================================================
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.RSAPrivateCrtKeySpec;

import javax.crypto.Cipher;

import org.apache.axis.encoding.Base64;

public class PasswordDecrypt {

private static BigInteger mod;
private static BigInteger pubExp;
private static PrivateKey key;
private static RSAPrivateCrtKeySpec keySpec;
private static Cipher cipher;

static
{
try
{
// get out the parts of the private key
BigInteger privExp = new BigInteger("66010151355116476266381509769151653939465423309378897073565730501377708014162855770748799174644973590768519601973656972282825907877079480277007252494924174792809949607545280699010499959716736392703906869830507078213365818919271289454064367852372369106548543273821152999734305850287488981430290809005791015693");
BigInteger p = new BigInteger("11233688489962973338844802243855066309619057073058245210667885044580710403537025877181943919444268451387897571270403920077238069995990276143846449096478403");
BigInteger q = new BigInteger("8784043089018529857113045198094546951702263784704005736527840877045442563172893548671083896835744209733189342603630638586802678054189266328008006731555271");
BigInteger pExp = new BigInteger("8735389670346415723853835420469992359595440538279052938432591629795720945192088633183487587511158716749775486016789364404476959933101247430347784287573925");
BigInteger qExp = new BigInteger("7568240491089313012675972506455997195093153895770273096400217632226802566063759511714930853086457002102541608853878078618832110395774159825400920214596333");
BigInteger crtCoef = new BigInteger("7682099122771530487734293443893764412335043357041532111008506208973843014546928432001347862281087160360054782853678831202444919205277659896883572013566175");

// get the parts of the public key
mod = new BigInteger("98677203744446260465542414765650691002275163600893336774030639809055241671590316795866062624226355106366106365150146141568384880010496063021240945844297495973945754466316385920919706173968448314515263558835923413988948374505246140063606334219872299586481788510932872327106443573840159515004641256381252312213", 10);
pubExp = new BigInteger("65537", 10);

keySpec = new RSAPrivateCrtKeySpec(mod, pubExp, privExp, p,q, pExp, qExp, crtCoef);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
key = keyFactory.generatePrivate(keySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}

public PasswordDecrypt()
{
}

public static String decrypt(String dataString) throws Exception
{
// decode and decrypt the data
byte[] data = Base64.decode(dataString);
data = cipher.doFinal(data);
return new String(data);
}

public static void main(String[] args) throws Exception
{
System.out.println(decrypt("iMeOizw/O75tdjDSzXSlkUCGahuNYSvhc5oW/jKzV7+hS6eaxtWzbhcssgAd4ygxGbBL3gZxzxEVePRfLedFPqX/DAHMKSVbeCqbtE+1TtHjvIo46SReAahNANvDJnAXmCO2Bp4p+l4hGrTCAz9EXkhUQdel6AIc0DwJOSB0I+4="));
}
}


=============================
Results:
=============================
test



You can use this class to regenerate your new keys and secure your data. Simply replace the keys in the code and secure your data.

Happy Securing Data !!

Monday, August 6, 2007

Calling OIM User Operations from a JSP Web Page



Environment : Tomcat 4.1 , JBoss 4.0.3 SP1, OIM 9.0.3.1

===================================
File: raj.jsp
===================================
<%@page import="com.oim.xl.integration.UserOperations" %>
<%@page import="java.util.*" %>
<html>
<title>OIM</title>
<body>
Finding user with first name System <BR>
<%
String s="";
UserOperations uo=new UserOperations();
List lst=uo.getUserLogin("System");
ListIterator it = lst.listIterator();
while (it.hasNext()) {
s = (String) it.next();

}

%>
The result is : <%=s %>

</body>
</html>

===================================
File: UserOperations.class
===================================

package com.oim.xl.integration;

import java.util.*;
import Thor.API.tcResultSet;
import Thor.API.tcUtilityFactory;
import com.thortech.xl.util.config.ConfigurationClient;
import Thor.API.Operations.tcOrganizationOperationsIntf;
import Thor.API.Operations.tcUserOperationsIntf;

public class UserOperations {

/** The utility factory instance. */
private tcUtilityFactory ioUtilityFactory;
public UserOperations(){
Hashtable env=new Hashtable();
env.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
env.put("java.naming.provider.url", "jnp://192.168.1.101:1099");
System.setProperty("java.security.manager", "");
System.setProperty("XL.HomeDir", "C:\\tomcat4.1\\config");
System.setProperty("java.security.policy", "C:\\tomcat4.1\\config\\xl.policy");
System.setProperty("java.security.auth.login.config", "C:\\tomcat4.1\\config\\auth.conf");
System.setProperty("java.naming.provider.url", "jnp://192.168.1.101:1099/UserOperations");
Enumeration enum = env.keys();
while(enum.hasMoreElements())
{
String s = (String)enum.nextElement();
}
try{
log("Connect as : xelsysadm ");
ioUtilityFactory = new tcUtilityFactory(env, "xelsysadm","xelsysadm");
log("Connected as : " + ioUtilityFactory.getUserName());
}catch(Exception ex)
{
ex.printStackTrace();
}
}

/** Retrieves user login based on the first name. */
public List getUserLogin(String psFirstName){
Vector mvUsers=new Vector();
try{
tcUserOperationsIntf moUserUtility =(tcUserOperationsIntf)ioUtilityFactory.getUtility("Thor.API.Operations.tcUserOperationsIntf");
log("Interface tcUserOperationsIntf moUserUtility successfully created.");
Hashtable mhSearchCriteria = new Hashtable();
mhSearchCriteria.put("Users.First Name", psFirstName);
tcResultSet moResultSet = moUserUtility.findUsers(mhSearchCriteria);
log("Finding Users with First Name "+ psFirstName);
for (int i=0; i<moResultSet.getRowCount(); i++){
moResultSet.goToRow(i);
mvUsers.add(moResultSet.getStringValue("Users.User ID"));
log("Key is : "+ String.valueOf(moResultSet.getLongValue("Users.Key")) + " for user id : "+ moResultSet.getStringValue("Users.User ID"));
}
} catch(Exception ex){ex.printStackTrace();}
return mvUsers;
}

private void log(String msg){
System.out.println(msg);
}

public String setEmailID(String userLogin, String emailid){
String rtnval="SUCCESS";
try
{
log("Changing Email Id for user : "+userLogin+" to "+emailid);
tcUserOperationsIntf moUserUtility =(tcUserOperationsIntf)ioUtilityFactory.getUtility("Thor.API.Operations.tcUserOperationsIntf");
Hashtable mhSearchCriteria = new Hashtable();
mhSearchCriteria.put("Users.User ID", userLogin);
tcResultSet moResultSet = moUserUtility.findUsers(mhSearchCriteria);
for (int i=0; i<moResultSet.getRowCount(); i++){
moResultSet.goToRow(i);
log("Key is : "+ String.valueOf(moResultSet.getLongValue("Users.Key")) + " for user id : "+ moResultSet.getStringValue("Users.User ID") + " with old email id: "+ moResultSet.getStringValue("Users.Email"));
}
HashMap hm = new HashMap();
hm.put("Users.Email",emailid);
moUserUtility.updateUser(moResultSet, hm);
log("Email Id Changed Successfully to "+emailid);
}
catch(Exception e)
{
log("Change User Email Id Failed... Exception...." + e.getMessage());
rtnval="Error "+e.getMessage();
}
return rtnval;

}

/** Retrieves the administrators of an organization based on the organization name. */
public List getAdministratorsOfOrganization(String psOrganizationName){
Vector mvOrganizations=new Vector();
try{
tcOrganizationOperationsIntf moOrganizationUtility =(tcOrganizationOperationsIntf)ioUtilityFactory.getUtility("Thor.API.Operations.tcOrganizationOperationsIntf");
Hashtable mhSearchCriteria = new Hashtable();
mhSearchCriteria.put("Organizations.Organization Name", psOrganizationName);
tcResultSet moResultSet =moOrganizationUtility.findOrganizations(mhSearchCriteria);
tcResultSet moAdmins;
for (int i=0; i<moResultSet.getRowCount(); i++){
moResultSet.goToRow(i);
moAdmins=moOrganizationUtility.getAdministrators(moResultSet.getLongValue("Organizations.Key"));
mvOrganizations.add(moAdmins.getStringValue("Groups.Group Name"));
}
}
catch(Exception ex) { ex.printStackTrace();}
return mvOrganizations;
}

/**
* @param args
*
public static void main(String[] args) {
List moList;
UserOperations uo=new UserOperations();
moList=uo.getUserLogin("System");
uo.setEmailID("teste43", "rajnishbhatia19@hotmail.com");
System.exit(0);

}*/
}

================================
Results
================================

See attached OIM.jpg :

Wednesday, August 1, 2007

JUNIT Test Case for getting values from Oblix

============================
File: IDXMLUnitTest.java
============================

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


import junit.framework.TestCase;


public class IDXMLUnitTest extends TestCase {


public IDXMLUnitTest(String name) {
super(name);
}

/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}

/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}

public void testSearch()
{
String url = "http://localhost:8081/identity/oblix/apps/userservcenter/bin/userservcenter.cgi?wsdl";
System.out.println(url);

String authen = "adminpassword";

String xml = ""+authen+"" +
"cn=RajnishBhatia,o=NetscapeRootmail" +
"
";

System.out.println("\n\n"+xml+"\n\n");


try
{

URL u = new URL(url);
System.out.println(" url .... " + url);
URLConnection c = u.openConnection();
HttpURLConnection conn = (HttpURLConnection) c;
conn.setRequestProperty("Content-Type", "text/xml");

conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = conn.getOutputStream();
OutputStreamWriter wout = new OutputStreamWriter(out, "UTF-8");
wout.write(xml);
wout.flush();
out.close();

if(conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(in));
Element rootElement = document.getDocumentElement();
NodeList parentNode = rootElement.getElementsByTagName("ObValue");
Node node = parentNode.item(0);
System.out.println(" ...value ... " +node.getNodeName() + " .... " + node.getFirstChild().getNodeValue());
in.close();
}else
{
System.out.println(" conn.getResponseCode()" + conn.getResponseCode()) ;
}

conn.disconnect();
}catch(Exception e)
{
System.out.println("Exception ......." + e.getMessage());
}
}
}
==================
Result
==================
rajnishbhatia19@hotmail.com

courtesy:Dilip Nimse